我想运行一些命令并抓取输出到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中的文本[-1:]行…但我似乎无法在第二版中做类似的事情.任何人都可以解释我需要做什么才能使第二个函数生成与第一个函数相同的输出而在它们之间没有额外的行(并且在最后)?
更新:这是我打印输出的方式
这就是我打印的方式
status,output,error = Getstatusoutput2(cmd)
s,oldOutput = Getstatusoutput(cmd)
print "oldOutput = <<%s>>" % (oldOutput)
print "error = <<%s>>" % (error)
最佳答案
您可以添加.strip():
原文链接:https://www.f2er.com/python/439212.htmldef Getstatusoutput2(cmd):
proc = subprocess.Popen(cmd,proc.stdout.read().strip(),proc.stderr.read().strip()
string.strip(s[,chars])
Return a copy of the string with leading and
trailing characters removed. Ifchars
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.