我有一个简单的脚本,用于在测试中自动调用我们的软件(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")
<小时/> 当我运行它(我最近将我的Python升级到Python 3.1.2)时,我现在收到以下错误:
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
<小时/> 看来,communic()调用返回字节数组,但在python解释器中,如果我
dir(bytes)
,我仍然可以看到strip()和replace()函数。有谁知道如何做到这一点?
感谢。
答案 0 :(得分:3)
bytes.replace()
期望字节作为参数:
crOut.strip().replace(b"><", b">\n<").replace(b"\" ", b"\"\n")
虽然通常最好尽可能早地将输入解码为unicode文本。并且要对文本执行转换(而不是字节)。
答案 1 :(得分:1)
您需要使用crOut.decode("utf-8")
并在返回的字符串中执行.replace。
答案 2 :(得分:1)
在python 3.2中,使用decode('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.