将subprocess.Popen调用的输出存储在一个string中

我试图在Python中进行系统调用,并将输出存储为一个string,我可以在Python程序中进行操作。

#!/usr/bin/python import subprocess p2 = subprocess.Popen("ntpq -p") 

我已经尝试了一些东西,包括这里的一些build议:

检索subprocess.call()的输出

但没有任何运气。

在Python 2.7或Python 3中

您可以使用subprocess.check_output()函数将命令的输出存储在string中,而不是直接创buildPopen对象:

 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"]

这对我redirect标准输出(stderr可以类似地处理):

 from subprocess import Popen, PIPE pipe = Popen(path, stdout=PIPE) text = pipe.communicate()[0] 

如果它不适用于您,请详细说明您遇到的问题。

假设pwd只是一个例子,你可以这样做:

 import subprocess p = subprocess.Popen("pwd", stdout=subprocess.PIPE) result = p.communicate()[0] print result 

有关其他示例和更多信息,请参阅子stream程文档 。

subprocess.Popen: http : //docs.python.org/2/library/subprocess.html#subprocess.Popen

 import subprocess command = "ntpq -p" # the shell command process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True) #Launch the shell command: output = process.communicate() print output[0] 

在Popen构造函数中,如果shellTrue ,则应该将该命令作为string传递,而不是作为序列传递。 否则,只需将命令分成一个列表:

 command = ["ntpq", "-p"] # the shell command process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None) 

如果您还需要读取标准错误,请在Popen初始化中,将stderr设置为subprocess.PIPEsubprocess.STDOUT

 import subprocess command = "ntpq -p" # the shell command process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) #Launch the shell command: output, error = process.communicate() 

这对我来说是完美的:

 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 

对于Python 2.7+,惯用的答案是使用subprocess.check_output subprocess.check_output()

你也应该注意到在调用一个subprocess时处理参数,因为它可能有点混乱。

如果args只是单个命令而没有自己的参数(或者你有shell=True set),它可以是一个string。 否则,它必须是一个列表。

例如…来调用ls命令,这是很好的:

 from subprocess import check_call check_call('ls') 

所以是这样的:

 from subprocess import check_call check_call(['ls',]) 

然而,如果你想传递一些参数给shell命令,你不能这样做:

 from subprocess import check_call check_call('ls -al') 

相反,你必须把它作为一个列表来传递:

 from subprocess import check_call check_call(['ls', '-al']) 

在创build子shlex.split()函数有时可以将string拆分为类似shell的语法,如下所示:

 from subprocess import check_call import shlex check_call(shlex.split('ls -al')) 
  import os list = os.popen('pwd').read() 

在这种情况下,你将只有一个元素在列表中。

我在这里写了一个基于其他答案的小函数:

 def pexec(*args): return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].rstrip() 

用法:

 changeset = pexec('hg','id','--id') branch = pexec('hg','id','--branch') revnum = pexec('hg','id','--num') print('%s : %s (%s)' % (revnum, changeset, branch)) 

这对我来说是完美的。 你会得到一个元组中的返回码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]