【发布时间】:2011-10-03 05:10:27
【问题描述】:
我想在 python 脚本中获取一些 shell 命令的输出,例如 ls 或 df。我看到 commands.getoutput('ls') 已被弃用,但 subprocess.call('ls') 只会让我得到返回码。
我希望有一些简单的解决方案。
【问题讨论】:
标签: python shell command subprocess
我想在 python 脚本中获取一些 shell 命令的输出,例如 ls 或 df。我看到 commands.getoutput('ls') 已被弃用,但 subprocess.call('ls') 只会让我得到返回码。
我希望有一些简单的解决方案。
【问题讨论】:
标签: python shell command subprocess
使用subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
请注意,通信会阻塞,直到进程终止。如果您需要在输出终止之前输出,您可以使用 process.stdout.readline()。如需更多信息,请参阅documentation。
【讨论】:
subprocess 示例的 Python 2.7 版本的正确当前文档链接是:docs.python.org/library/…;对于 Python 3.2,docs.python.org/py3k/library/…
out 工作正常,但err 将未初始化并且错误输出会打印到屏幕上。除了 stdout 之外,您还必须指定 stderr=subprocess.PIPE 才能获得标准错误。
对于 Python >= 2.7,使用 subprocess.check_output()。
http://docs.python.org/2/library/subprocess.html#subprocess.check_output
【讨论】:
subprocess.check_output(cmd, shell=True)。
要使用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
【讨论】: