在Python 3中使用子进程

3

我正在使用subprocess模块在Python 3中运行shell命令。以下是我的代码:

import subprocess
filename = "somename.py"  # in practical i'm using a real file, this is just for example
subprocess.call("pep8 %s" % filename, shell=True)) 

不同文件的输出只有0或1。我对Python 3很陌生。在2.7中使用此功能可以得到所需的输出,但是我现在无法弄清楚。
以下是在Python 2.7中对于名为“anu.py”的文件所获得的输出:
anu.py:2:1: W191 indentation contains tabs
anu.py:3:1: W191 indentation contains tabs
anu.py:3:7: E228 missing whitespace around modulo operator
anu.py:4:1: W191 indentation contains tabs
anu.py:5:1: W191 indentation contains tabs
anu.py:6:1: W191 indentation contains tabs
anu.py:7:1: W191 indentation contains tabs
anu.py:7:9: E231 missing whitespace after ','
anu.py:8:1: W191 indentation contains tabs
anu.py:9:1: W191 indentation contains tabs
1

请大家帮帮我。 谢谢
更新:
我尝试使用subprocess.check_output方法, 以下是我得到的输出结果,
>>> subprocess.check_output(["pep8", "anu.py"])
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "X/subprocess.py", line 584, in check_output
it too will be used internally.  Example:
subprocess.CalledProcessError: Command '['pep8', 'anu.py']' returned non-zero exit status 1
1个回答

7
subprocess.call 只会返回运行的进程的退出码。通常建议使用subprocess.check_output,它将返回子进程的实际输出。然而,在您特定的情况下,pep8 在某些情况下会返回非零的退出码,这会导致check_output引发异常。您可以捕获异常并从中提取输出属性:
try:
    output = subprocess.check_output(['pep8', 'anu.py'])
except subprocess.CalledProcessError as e:
    output = e.output

或者直接使用 subprocess.Popen
p = subprocess.Popen(['pep8', 'anu.py'], stdout=subprocess.PIPE)
(output, _) = p.communicate()

请注意,call在Python 2.x和Python 3.x之间的行为没有改变。你看到的行为差异可能是因为你在交互式提示符中运行了Python 2.7,但作为实际脚本运行了Python 3版本。即使在交互提示符中使用subprocess.call,它仍然会打印调用的输出,尽管函数实际上并没有返回该输出。

你为什么要使用这个 (output, _) - Anurag-Sharma
1
p.communicate() 返回元组 (stdoutdata, stderrdata)。我们只对 stdout 感兴趣。一个常见的 Python 约定是使用 _ 作为我们实际上不感兴趣的元组参数的变量。 - dano
非常感谢您的帮助,现在它已经可以工作了,只是我需要将它解码为“utf-8”。 - Anurag-Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接