[英]python subprocess: order of output changes when using subprocess.PIPE
[英]Python 3 subprocess.PIPE output error
我有一个简单的脚本,可以在测试中使用它来自动化对软件(Moab工作负载管理器)的CLI调用,从而避免使用'--xml'标志获取xml输出,然后将其通过整洁的方式进行管道传输,以便于阅读。 它使用subprocess.Popen
调用运行命令,然后使用str.strip()
和str.replace()
上做返回的XML未成年人清理,以方便目视检查。 有问题的代码在这里:
cmdString = "%s --xml" % cmd
cmdList = cmdString.split()
cmdRun = subprocess.Popen(cmdList,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
crOut,crErr = cmdRun.communicate()
xmlOutput = crOut.strip().replace("><",">\n<").replace("\" ","\"\n")
Traceback (most recent call last): File "/usr/local/bin/xmlcmd", line 50, in <module> runXMLCmd(getCmd()) File "/usr/local/bin/xmlcmd", line 45, in runXMLCmd xmlOutput = crOut.strip().replace("><",">\\n<") TypeError: expected an object with the buffer interface
dir(bytes)
我仍然可以看到strip()和replace()函数。
有人知道如何做到这一点吗?
谢谢。
bytes.replace()
期望字节作为参数:
crOut.strip().replace(b"><", b">\n<").replace(b"\" ", b"\"\n")
尽管通常来说,最好将输入解码为尽可能早的unicode文本。 以及要在文本(不是字节)上执行的转换。
您需要使用crOut.decode("utf-8")
并在返回的字符串中执行.replace。
在python 3.2中,使用encode('ascii')修复了一些unicode和类型错误,这些错误很难跟踪。 无论字节还是字节数组,解码都将根据需要转换为字符串。
pipe = subprocess.Popen("cmd", 1024, stdout=subprocess.PIPE)
while pipe.returncode == None:
lines = pipe.communicate()[0]
lines = lines.decode('ascii')
for line in lines.splitlines():
if (re.search('^---', line)):
pass # do stuff
从手册中
bytes.decode(encoding="utf-8", errors="strict")
bytearray.decode(encoding="utf-8", errors="strict")
Return a string decoded from the given bytes.
Default encoding is 'utf-8'. errors may be given to set a
different error handling scheme.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.