将 subprocess.Popen 调用的输出存储在字符串中 [英] Store output of subprocess.Popen call in a string
问题描述
我正在尝试在 Python 中进行系统调用并将输出存储到我可以在 Python 程序中操作的字符串中.
I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")
我尝试了一些方法,包括这里的一些建议:
I've tried a few things including some of the suggestions here:
但没有任何运气.
推荐答案
在 Python 2.7 或 Python 3 中
您可以使用 Popen 对象="noreferrer">subprocess.check_output()
函数 将命令的输出存储在字符串中:
Instead of making a Popen
object directly, you can use the subprocess.check_output()
function to store output of a command in a string:
from subprocess import check_output
out = check_output(["ntpq", "-p"])
在 Python 2.4-2.6 中
使用communicate
方法.
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()
out
就是你想要的.
关于其他答案的重要说明
注意我是如何传递命令的."ntpq -p"
示例提出了另一个问题.由于 Popen
不调用 shell,您将使用命令和选项列表——["ntpq", "-p"]
.
Note how I passed in the command. The "ntpq -p"
example brings up another matter. Since Popen
does not invoke the shell, you would use a list of the command and options—["ntpq", "-p"]
.
这篇关于将 subprocess.Popen 调用的输出存储在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!