python - 子进程检查输出错误

标签 python subprocess

我正在尝试使用下面的脚本检查 check_output 的用法并遇到编译错误,我哪里出错了?

import os
import subprocess
from subprocess import check_output

#result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])
SCRIPT_ROOT=subprocess.check_output(["pwd","shell=True"])
print SCRIPT_ROOT

def main ():
    pass

if __name__ == '__main__':
    main()

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    from subprocess import check_output
ImportError: cannot import name check_output

最佳答案

check_output 已在 Python 2.7 中引入。如果您使用的是早期版本的 python,它就不会存在。

另一种方法是使用 Popen

output = subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0]

可以找到这方面的证明 here .

New function: the subprocess module’s check_output() runs a command with a specified set of arguments and returns the command’s output as a string when the command runs without error, or raises a CalledProcessError exception otherwise.

替代品演示。

import subprocess
cmd = subprocess.Popen(['pwd'], stdout=subprocess.PIPE)
output = cmd.communicate()[0]
print cmd.returncode
print output

输出

> python p.py
/Users/vlazarenko/tests

唯一真正的区别是 Popen 在命令返回非零代码时不会抛出异常。

关于python - 子进程检查输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063027/

相关文章:

python - 将分隔符从分号转换为 CSV 中的逗号?

python - 通过子进程模块在Python中剪切命令

python - 使用 python subprocess/sh 作为 bash 包装器的问题

python - 如何正确转义python子进程中的特殊字符?

Python 子进程 (ffmpeg) 仅在我按 Ctrl-C 程序时启动?

python - 如何避免 Django View 中的重复代码?

Python BeautifulSoup 编码

python - 无法访问 postgresql 表

python:从文本导入数据

python子进程和mysqldump