【问题标题】:Using subprocess in python 3在 python 3 中使用子进程
【发布时间】:2014-06-05 02:54:52
【问题描述】:

我使用 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)) 

不同文件的输出只是01。我对 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

【问题讨论】:

    标签: python python-3.x subprocess


    【解决方案1】:

    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, _)??
    • p.communicate() 返回元组 (stdoutdata, stderrdata)。我们只对标准输出感兴趣。一个常见的 Python 约定是使用 _ 作为我们实际上并不感兴趣的元组参数的变量。
    • 非常感谢您的帮助,现在它可以工作了,我只需将其解码为 'utf-8'
    猜你喜欢
    • 2019-06-28
    • 2012-03-15
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2015-02-03
    相关资源
    最近更新 更多