在Python 3中使用subprocess

3 投票
1 回答
2932 浏览
提问于 2025-04-18 08:40

我在用Python 3的subprocess模块来运行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)) 

不同文件的输出结果只有01。我对Python 3还很陌生。在Python 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 仍然会打印出调用的输出,尽管这个输出并没有被函数实际返回。

撰写回答