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.
我尝试在Python中创建一个系统调用,并将输出存储到我可以在Python程序中操作的字符串中。
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")
I've tried a few things including some of the suggestions here:
我尝试了一些东西,包括一些建议:
Retrieving the output of subprocess.call()
检索子进程的输出。
but without any luck.
但是没有任何运气。
9 个解决方案
#1
358
In Python 2.7 or Python 3
在Python 2.7或Python 3中。
Instead of making a Popen
object directly, you can use the subprocess.check_output()
function to store output of a command in a string:
您可以使用subprocess.check_output()函数将一个命令的输出存储在字符串中,而不是直接创建一个Popen对象。
from subprocess import check_output
out = check_output(["ntpq", "-p"])
In Python 2.4-2.6
在Python 2.4 - -2.6
Use the communicate
method.
使用交流方法。
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()
out
is what you want.
你想要的就是出去。
Important note about the other answers
关于其他答案的重要提示。
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"]
.
注意我是如何通过命令的。“ntpq -p”的例子引出了另一个问题。由于Popen不调用shell,所以您将使用命令和选项列表—[“ntpq”,“-p”]。
#2
33
This worked for me for redirecting stdout (stderr can be handled similarly):
这对我来说是为了重定向stdout (stderr可以类似地处理):
from subprocess import Popen, PIPE
pipe = Popen(path, stdout=PIPE)
text = pipe.communicate()[0]
If it doesn't work for you, please specify exactly the problem you're having.
如果它对你不起作用,请详细说明你的问题。
#3
19
Assuming that pwd
is just an example, this is how you can do it:
假设pwd只是一个例子,那么您可以这样做:
import subprocess
p = subprocess.Popen("pwd", stdout=subprocess.PIPE)
result = p.communicate()[0]
print result
See the subprocess documentation for another example and more information.
有关另一个示例和更多信息,请参阅子流程文档。
#4
16
subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
子流程。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]
In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:
在Popen构造函数中,如果shell是True,那么您应该将命令作为字符串传递,而不是按顺序传递。否则,只需将命令分解为一个列表:
command = ["ntpq", "-p"] # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:
如果您需要读取标准错误,进入Popen初始化,您可以将stderr设置为子进程。管道或subprocess.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()
#5
10
This works perfectly for me:
这对我来说是完美的:
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
#6
7
for Python 2.7+ the idiomatic answer is to use subprocess.check_output()
对于Python 2.7+的惯用答案是使用subprocess.check_output()
You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....
你也应该注意当调用子流程的处理参数,因为它可能会让人有些迷惑....
If args is just single command with no args of its own (or you have shell=True
set), it can be a string. Otherwise it must be a list.
如果args只是单个命令,而没有自己的args(或者您有shell=True set),那么它可以是一个字符串。否则它必须是一个列表。
for example... to invoke the ls
command, this is fine:
例如……要调用ls命令,这很好:
from subprocess import check_call
check_call('ls')
so is this:
所以是这样的:
from subprocess import check_call
check_call(['ls',])
however, if you want to pass some args to the shell command, you can't do this:
但是,如果您想要传递一些args到shell命令,您不能这样做:
from subprocess import check_call
check_call('ls -al')
instead, you must pass it as a list:
相反,你必须把它作为一个列表来传递:
from subprocess import check_call
check_call(['ls', '-al'])
the shlex.split()
function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses... like this:
split()函数在创建子进程之前,有时可以将字符串拆分为类似shell的语法。是这样的:
from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))
#7
4
import os
list = os.popen('pwd').read()
In this case you will only have one element in the list.
在这种情况下,列表中只有一个元素。
#8
4
I wrote a little function based on the other answers here:
我写了一个基于其他答案的函数
def pexec(*args):
return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].rstrip()
Usage:
用法:
changeset = pexec('hg','id','--id')
branch = pexec('hg','id','--branch')
revnum = pexec('hg','id','--num')
print('%s : %s (%s)' % (revnum, changeset, branch))
#9
3
This was perfect for me. You will get the return code, stdout and stderr in a tuple.
这对我来说太完美了。您将获得一个tuple中的返回代码、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)
For Example:
例如:
result = console('ls -l')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]
#1
358
In Python 2.7 or Python 3
在Python 2.7或Python 3中。
Instead of making a Popen
object directly, you can use the subprocess.check_output()
function to store output of a command in a string:
您可以使用subprocess.check_output()函数将一个命令的输出存储在字符串中,而不是直接创建一个Popen对象。
from subprocess import check_output
out = check_output(["ntpq", "-p"])
In Python 2.4-2.6
在Python 2.4 - -2.6
Use the communicate
method.
使用交流方法。
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()
out
is what you want.
你想要的就是出去。
Important note about the other answers
关于其他答案的重要提示。
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"]
.
注意我是如何通过命令的。“ntpq -p”的例子引出了另一个问题。由于Popen不调用shell,所以您将使用命令和选项列表—[“ntpq”,“-p”]。
#2
33
This worked for me for redirecting stdout (stderr can be handled similarly):
这对我来说是为了重定向stdout (stderr可以类似地处理):
from subprocess import Popen, PIPE
pipe = Popen(path, stdout=PIPE)
text = pipe.communicate()[0]
If it doesn't work for you, please specify exactly the problem you're having.
如果它对你不起作用,请详细说明你的问题。
#3
19
Assuming that pwd
is just an example, this is how you can do it:
假设pwd只是一个例子,那么您可以这样做:
import subprocess
p = subprocess.Popen("pwd", stdout=subprocess.PIPE)
result = p.communicate()[0]
print result
See the subprocess documentation for another example and more information.
有关另一个示例和更多信息,请参阅子流程文档。
#4
16
subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
子流程。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]
In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:
在Popen构造函数中,如果shell是True,那么您应该将命令作为字符串传递,而不是按顺序传递。否则,只需将命令分解为一个列表:
command = ["ntpq", "-p"] # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:
如果您需要读取标准错误,进入Popen初始化,您可以将stderr设置为子进程。管道或subprocess.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()
#5
10
This works perfectly for me:
这对我来说是完美的:
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
#6
7
for Python 2.7+ the idiomatic answer is to use subprocess.check_output()
对于Python 2.7+的惯用答案是使用subprocess.check_output()
You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....
你也应该注意当调用子流程的处理参数,因为它可能会让人有些迷惑....
If args is just single command with no args of its own (or you have shell=True
set), it can be a string. Otherwise it must be a list.
如果args只是单个命令,而没有自己的args(或者您有shell=True set),那么它可以是一个字符串。否则它必须是一个列表。
for example... to invoke the ls
command, this is fine:
例如……要调用ls命令,这很好:
from subprocess import check_call
check_call('ls')
so is this:
所以是这样的:
from subprocess import check_call
check_call(['ls',])
however, if you want to pass some args to the shell command, you can't do this:
但是,如果您想要传递一些args到shell命令,您不能这样做:
from subprocess import check_call
check_call('ls -al')
instead, you must pass it as a list:
相反,你必须把它作为一个列表来传递:
from subprocess import check_call
check_call(['ls', '-al'])
the shlex.split()
function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses... like this:
split()函数在创建子进程之前,有时可以将字符串拆分为类似shell的语法。是这样的:
from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))
#7
4
import os
list = os.popen('pwd').read()
In this case you will only have one element in the list.
在这种情况下,列表中只有一个元素。
#8
4
I wrote a little function based on the other answers here:
我写了一个基于其他答案的函数
def pexec(*args):
return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].rstrip()
Usage:
用法:
changeset = pexec('hg','id','--id')
branch = pexec('hg','id','--branch')
revnum = pexec('hg','id','--num')
print('%s : %s (%s)' % (revnum, changeset, branch))
#9
3
This was perfect for me. You will get the return code, stdout and stderr in a tuple.
这对我来说太完美了。您将获得一个tuple中的返回代码、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)
For Example:
例如:
result = console('ls -l')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]