我试图在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()的输出
但运气不好。
当前回答
对于python 3.5,我根据前面的回答提出了函数。原木可能被移除,但它很好
import shlex
from subprocess import check_output, CalledProcessError, STDOUT
def cmdline(command):
log("cmdline:{}".format(command))
cmdArr = shlex.split(command)
try:
output = check_output(cmdArr, stderr=STDOUT).decode()
log("Success:{}".format(output))
except (CalledProcessError) as e:
output = e.output.decode()
log("Fail:{}".format(output))
except (Exception) as e:
output = str(e);
log("Fail:{}".format(e))
return str(output)
def log(msg):
msg = str(msg)
d_date = datetime.datetime.now()
now = str(d_date.strftime("%Y-%m-%d %H:%M:%S"))
print(now + " " + msg)
if ("LOG_FILE" in globals()):
with open(LOG_FILE, "a") as myfile:
myfile.write(now + " " + msg + "\n")
其他回答
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():
希望能有所帮助,编码愉快
这对我来说太完美了。 您将在元组中获得返回代码、stdout和stderr。
from subprocess import Popen, PIPE
def console(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
out, err = p.communicate()
return (p.returncode, out, err)
例如:
result = console('ls -l')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]
下面将在单个变量中捕获流程的stdout和stderr。它兼容Python 2和3:
from subprocess import check_output, CalledProcessError, STDOUT
command = ["ls", "-l"]
try:
output = check_output(command, stderr=STDOUT).decode()
success = True
except CalledProcessError as e:
output = e.output.decode()
success = False
如果你的命令是一个字符串而不是一个数组,用前缀this:
import shlex
command = shlex.split(command)
Python 2: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
from subprocess import PIPE, Popen
command = "ntpq -p"
process = Popen(command, stdout=PIPE, stderr=None, shell=True)
output = process.communicate()[0]
print output
在Popen构造函数中,如果shell为True,则应该将命令作为字符串而不是序列传递。否则,只需将命令拆分为一个列表:
command = ["ntpq", "-p"]
process = Popen(command, stdout=PIPE, stderr=None)
如果你还需要读取标准错误到Popen初始化中,你应该将stderr设置为PIPE或STDOUT:
command = "ntpq -p"
process = subprocess.Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
output, error = process.communicate()
注意:从Python 2.7开始,你可以/应该利用subprocess。# subprocess.check_output check_output (https://docs.python.org/2/library/subprocess.html)。
Python 3: https://docs.python.org/3/library/subprocess.html#subprocess.Popen
from subprocess import PIPE, Popen
command = "ntpq -p"
with Popen(command, stdout=PIPE, stderr=None, shell=True) as process:
output = process.communicate()[0].decode("utf-8")
print(output)
注意:如果你的目标只是Python版本高于或等于3.5,那么你可以/应该利用subprocess.run (https://docs.python.org/3/library/subprocess.html#subprocess.run)。