繁体   English   中英

Python 3子进程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")


运行此命令时(我最近将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 


看来communication()调用正在返回字节数组,但是在python解释器中,如果我执行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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM