Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用subprocess.call方法_Python - Fatal编程技术网

Python 使用subprocess.call方法

Python 使用subprocess.call方法,python,Python,Python版本:“2.6.5(r265:79063,2012年10月1日,22:07:21)\n[GCC 4.4.3]” 我有这个: >>> ss = subprocess.call("ls -z", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 现在如何获取错误消息 这不起作用: >>> for i in subprocess.PIPE: ... print i ...

Python版本:“2.6.5(r265:79063,2012年10月1日,22:07:21)\n[GCC 4.4.3]”

我有这个:

>>> ss = subprocess.call("ls -z", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
现在如何获取错误消息

这不起作用:

>>> for i in subprocess.PIPE:
...     print i
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
subprocess.PIPE中的i的
>:
...     打印i
... 
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“int”对象不可编辑

这个选项组合不太好用。Communicate()将读取stdout、stderr并等待程序终止

proc = subprocess.Popen("ls -z", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
assert proc.returncode == 0, 'i am sad'
print out
print err

如果您想在程序运行时逐行读取stdout,可以创建自己的线程来babysit stderr或将stderr管道到stdout。

我知道我可以打开。我想知道我该如何处理subprocess.call?call()不提供对管道的访问权限—它适用于希望用户查看输出或通过管道访问文件的情况。如果你想处理输出流,它就不是合适的工具。这并不能解释实际的错误
subprocess.PIPE
只是一个神奇的常量,它告诉
subprocess
函数在传递它时“创建一个新管道并在此处使用”。(它正好是-1,但这并不重要。)因此,迭代该神奇常量不会有任何用处。您使用
shell=True
“ls-z”
而不是
[“ls”,“-z”]
有什么原因吗?这与您的问题无关,但一般来说,在不需要的时候使用shell是一个坏主意,传递命令行并希望您正确地进行转义,以便将它们解析到您想要的列表中。