python getoutput()在子进程中的等价物

Raf*_*l T 60 python shell command subprocess

我想从像一些shell命令得到的输出ls或者df在Python脚本.我看到它commands.getoutput('ls')已被弃用,但subprocess.call('ls')只会给我返回代码.

我希望有一些简单的解决方案.

Mic*_*ith 86

使用subprocess.Popen:

import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE)
out, err = process.communicate()
print(out)
Run Code Online (Sandbox Code Playgroud)

请注意,通信阻塞直到进程终止.如果在终止之前需要输出,则可以使用process.stdout.readline().有关更多信息,请参阅文档.

  • 您可能需要使用process.communicate()替换subprocess.communicate() - 您可能还需要通过process.returncode来获取子进程退出代码. (5认同)
  • 适用于`out`,但是`err`将是未初始化的,并且错误输出将打印到屏幕上.除了`stdout`之外,你还必须指定`stderr = subprocess.PIPE`来获得标准错误. (3认同)

kni*_*ite 47

对于Python> = 2.7,请使用subprocess.check_output().

http://docs.python.org/2/library/subprocess.html#subprocess.check_output

  • 从技术上讲,它应该是`subprocess.check_output(cmd,shell = True)`. (6认同)
  • 我认为它支持"shell特定功能",如文件通配,管道等... (2认同)

Roi*_*ton 8

要捕获错误subprocess.check_output(),您可以使用CalledProcessError. 如果要将输出用作字符串,请从字节码中对其进行解码。

# \return String of the output, stripped from whitespace at right side; or None on failure.
def runls():
    import subprocess
    try:
        byteOutput = subprocess.check_output(['ls', '-a'], timeout=2)
        return byteOutput.decode('UTF-8').rstrip()
    except subprocess.CalledProcessError as e:
        print("Error in ls -a:\n", e.output)
        return None
Run Code Online (Sandbox Code Playgroud)