执行命令并将其输出存储在变量中

2024-06-13 08:39:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试编写一个python脚本,其中包括调用一个可执行文件并将该可执行文件发送给stdout的内容存储在一个变量中。以下是我所拥有的:

 1 #!/usr/bin/python
  2 import subprocess
  3 
  4 subprocess.call("./pmm", shell=True)

如何将pmm的输出存储在变量中?


Tags: import脚本true可执行文件内容binusrstdout
3条回答
p = subprocess.Popen(["./pmm"], shell=False, stdout=subprocess.PIPE)
output = p.stdout.read()

前段时间我写了一篇关于这个的帖子:

http://trifoliummedium.blogspot.com/2010/12/running-command-line-with-python-and.html

使用p.communicate()获取stdout和stderr

在Python2.7(和3.1或更高版本)中,可以使用^{}。文档中的示例:

>>> subprocess.check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

相关问题 更多 >