我试图在Python中进行系统调用,并将输出存储为我可以在Python程序中操作的字符串。
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")
我尝试了一些事情,包括这里的一些建议:
检索subprocess.call()的输出
但运气不好。
我试图在Python中进行系统调用,并将输出存储为我可以在Python程序中操作的字符串。
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")
我尝试了一些事情,包括这里的一些建议:
检索subprocess.call()的输出
但运气不好。
当前回答
使用子进程模块的check_output方法
import subprocess
address = '192.168.x.x'
res = subprocess.check_output(['ping', address, '-c', '3'])
最后解析字符串
for line in res.splitlines():
希望能有所帮助,编码愉快
其他回答
在Python 3.7+中,你可以为subprocess.run使用新的capture_output=关键字参数:
import subprocess
p = subprocess.run(["echo", "hello world!"], capture_output=True, text=True)
assert p.stdout == 'hello world!\n'
这对我来说非常合适:
import subprocess
try:
#prints results and merges stdout and std
result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
print result
#causes error and merges stdout and stderr
result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex: # error code <> 0
print "--------error------"
print ex.cmd
print ex.message
print ex.returncode
print ex.output # contains stdout and stderr together
import os
list = os.popen('pwd').read()
在这种情况下,列表中只有一个元素。
使用子进程模块的check_output方法
import subprocess
address = '192.168.x.x'
res = subprocess.check_output(['ping', address, '-c', '3'])
最后解析字符串
for line in res.splitlines():
希望能有所帮助,编码愉快
在Python 2.7或Python 3中
不用直接创建Popen对象,你可以使用subprocess.check_output()函数将命令的输出存储在字符串中:
from subprocess import check_output
out = check_output(["ntpq", "-p"])
在Python 2.4-2.6中
使用沟通方法。
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()
出去是你想要的。
关于其他答案的重要提示
注意我是如何传入命令的。“ntpq -p”示例引出了另一个问题。由于Popen不调用shell,因此可以使用命令和选项的列表- ["ntpq", "-p"]。