【发布时间】:2016-08-06 11:46:47
【问题描述】:
好的,所以。我正在编写一个非常基本的 Python 脚本,它只从 df -h 获取输出并将其显示在屏幕上。我打算实现一些其他功能,但这部分让我很困惑。
我很确定我的代码是正确的,我什至输入了 time.sleep() 语句来查看输出是否过快。但是,当我遍历标准输出时,即使使用 rstrip(),每次创建新行时,终端输出的间距都会很奇怪,并且会破坏终端。
有什么想法吗?
这是我的代码:
#!/usr/bin/python
import sys
import os
import re
import subprocess
import time
np1=subprocess.Popen('ssh -qt <redacted>/usr/bin/sudo df -h /opt/saswork', shell=True, stdout=subprocess.PIPE)
np2=subprocess.Popen('ssh -qt <redacted>/usr/bin/sudo df -h /opt/saswork', shell=True, stdout=subprocess.PIPE)
p1=subprocess.Popen('ssh -qt <redacted>/usr/bin/sudo df -h /opt/saswork', shell=True, stdout=subprocess.PIPE)
p2=subprocess.Popen('ssh -qt <redacted>/usr/bin/sudo df -h /opt/saswork', shell=True, stdout=subprocess.PIPE)
p3=subprocess.Popen('ssh -qt <redacted>/usr/bin/sudo df -h /opt/saswork', shell=True, stdout=subprocess.PIPE)
p4=subprocess.Popen('ssh -qt <redacted>/usr/bin/sudo df -h /opt/saswork', shell=True, stdout=subprocess.PIPE)
for x in np1.stdout:
x=x.rstrip()
x=re.findall('.\d%', x)
for y in x:
print "SAS Grid NP01 is at ", str(y)
time.sleep(1)
for x in np2.stdout:
x=x.rstrip()
x=re.findall('.\d%', x)
for y in x:
print "SAS Grid NP02 is at ", str(y)
time.sleep(1)
for x in p1.stdout:
x=x.rstrip()
x=re.findall('.\d%', x)
for y in x:
print "SAS Grid P01 is at ", str(y)
time.sleep(1)
for x in p2.stdout:
x=x.rstrip()
x=re.findall('.\d%', x)
for y in x:
print "SAS Grid P02 is at ", str(y)
time.sleep(1)
for x in p3.stdout:
x=x.rstrip()
x=re.findall('.\d%', x)
for y in x:
print "SAS Grid P03 is at ", str(y)
time.sleep(1)
for x in p4.stdout:
x=x.rstrip()
x=re.findall('.\d%', x)
for y in x:
print "SAS Grid P04 is at ", str(y)
这是输出
SAS Grid NP01 is at 33%
SAS Grid NP02 is at 36%
SAS Grid P01 is at 3%
SAS Grid P02 is at 23%
SAS Grid P03 is at 41%
SAS Grid P04 is at 24%
[<service account>@werindgatep01 ~]$
[<service account>@werindgatep01 ~]$
此时我必须做的是 CTRL-C 和 CTRL-D,直到它让我退出服务帐户并返回到我的标准用户帐户。从那里我可以 sudo su - 服务帐户
我迷路了。 . .迷路了
【问题讨论】:
-
在您提出下一个问题之前,请阅读How to Ask,更具体地说,请阅读minimal reproducible example。减小示例程序的大小并去除无关元素将提高您收到的响应的质量。
-
您使用的是什么操作系统?如果是Linux,什么发行版和版本?
-
print语句是在它打印的内容之间添加空格。每次在逗号分隔的列表中你给它它都会插入一个空格。为了更好地控制使用函数形式,或者只使用sys.stdout.write()方法。 -
如果在
Popen()之后添加print "abc"; print "def\r"; print "gh"会发生什么? -
我遇到了类似的问题,你能解决这个问题吗?
标签: python terminal subprocess output stdout