我想运行一些命令并获取输出到 stderr 的任何内容。我有两个版本的功能可以做到这一点 版本 1。
def Getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import sys
mswindows = (sys.platform == "win32")
import os
if not mswindows:
cmd = '{ ' + cmd + '; }'
pipe = os.popen(cmd + ' 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None: sts = 0
if text[-1:] == '\n': text = text[:-1]
return sts, text
和 版本 2
def Getstatusoutput2(cmd):
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()
return return_code, proc.stdout.read(), proc.stderr.read()
第一个版本如我所料打印 stderr 输出。第二个版本在每一行之后打印一个空行。我怀疑这是由于版本 1 中的 text[-1:] 行造成的......但我似乎无法在第二个版本中做类似的事情。任何人都可以解释我需要做什么才能使第二个函数生成与第一个函数相同的输出而中间(和最后)没有额外的行吗?
更新:这是我打印输出的方式 这是我打印的方式
status, output, error = Getstatusoutput2(cmd)
s, oldOutput = Getstatusoutput(cmd)
print "oldOutput = <<%s>>" % (oldOutput)
print "error = <<%s>>" % (error)
最佳答案
你可以添加.strip()
:
def Getstatusoutput2(cmd):
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
return_code = proc.wait()
return return_code, proc.stdout.read().strip(), proc.stderr.read().strip()
string.strip(s[, chars])
Return a copy of the string with leading and trailing characters removed. If
chars
is omitted orNone
, whitespace characters are removed. If given and notNone
,chars
must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.
string.whitespace
A string containing all characters that are considered whitespace. On most systems this includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
关于python subprocess proc.stderr.read() 引入额外的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7985334/