管道子流程标准输出到变量 [英] Pipe subprocess standard output to a variable
问题描述
我想使用子进程模块在pythong
中运行命令,并将输出存储在变量中.但是,我不希望将命令的输出打印到终端.
对于此代码:
I want to run a command in pythong
, using the subprocess module, and store the output in a variable. However, I do not want the command's output to be printed to the terminal.
For this code:
def storels():
a = subprocess.Popen("ls",shell=True)
storels()
我在终端中获得目录列表,而不是将其存储在a
中.我也尝试过:
I get the directory listing in the terminal, instead of having it stored in a
. I've also tried:
def storels():
subprocess.Popen("ls > tmp",shell=True)
a = open("./tmp")
[Rest of Code]
storels()
这也会将ls的输出打印到我的终端上.我什至使用过时的os.system方法尝试了此命令,因为在终端中运行ls > tmp
根本不会在终端上显示ls
,而是将其存储在tmp
中.但是,同样的事情也会发生.
This also prints the output of ls to my terminal. I've even tried this command with the somewhat dated os.system method, since running ls > tmp
in the terminal doesn't print ls
to the terminal at all, but stores it in tmp
. However, the same thing happens.
在遵循marcog的建议后,但仅在运行更复杂的命令时,才出现以下错误. cdrecord --help
. Python将其吐出:
I get the following error after following marcog's advice, but only when running a more complex command. cdrecord --help
. Python spits this out:
Traceback (most recent call last):
File "./install.py", line 52, in <module>
burntrack2("hi")
File "./install.py", line 46, in burntrack2
a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE)
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
推荐答案
To get the output of ls
, use stdout=subprocess.PIPE
.
>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo
命令cdrecord --help
输出到stderr,因此需要用管道传递该实例.您还应该按照下面的步骤将命令分解为一个令牌列表,或者替代方法是传递shell=True
参数,但这会触发一个成熟的shell,如果您不控制该shell可能会很危险.命令字符串的内容.
The command cdrecord --help
outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True
argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.
>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
-version print version information and exit
dev=target SCSI target to use as CD/DVD-Recorder
gracetime=# set the grace time before starting to write to #.
...
如果您有一个同时输出到stdout和stderr的命令,并且想要将它们合并,则可以通过将stderr传递到stdout然后捕获stdout来实现.
If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.
subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
如 Chris Morgan 所述,您应该使用proc.communicate()
而不是proc.read()
.
As mentioned by Chris Morgan, you should be using proc.communicate()
instead of proc.read()
.
>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout:
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
-version print version information and exit
dev=target SCSI target to use as CD/DVD-Recorder
gracetime=# set the grace time before starting to write to #.
...
这篇关于管道子流程标准输出到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!