将子流程标准输出转换为变量

我想使用子pythong模块在pythong运行一个命令,并将输出存储在一个变量中。 但是,我不希望将命令的输出打印到终端。 对于此代码:

def storels():
   a = subprocess.Popen("ls",shell=True)
storels()

我得到终端中的目录列表,而不是将它存储在a 。 我也试过:

 def storels():
       subprocess.Popen("ls > tmp",shell=True)
       a = open("./tmp")
       [Rest of Code]
 storels()

这也将ls的输出打印到我的终端。 我甚至用有点过时的os.system方法试过这个命令,因为在终端中运行ls > tmp根本不会将ls打印到终端,而是将它存储在tmp 。 然而,同样的事情发生。

编辑:

遵循marcog的建议后,我得到以下错误,但仅在运行更复杂的命令时出现。 cdrecord --help 。 Python吐出这个:

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

要获得ls的输出,请使用stdout=subprocess.PIPE

>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo

命令cdrecord --help输出到stderr,所以你需要管道indstead。 你也应该把命令分解成一个令牌列表,就像我在下面做的那样,或者另一种方法是传递shell=True参数,但是这会激发一个完全发生的shell,如果你不控制命令字符串的内容。

>>> 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来实现。

subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

正如Chris Morgan所提到的,您应该使用proc.communicate()而不是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 #.
...

如果您使用python 2.7或更高版本,最简单的方法是使用subprocess.check_output()命令。 这里是一个例子:

output = subprocess.check_output('ls')

要重定向stderr,您可以使用以下命令:

output = subprocess.check_output('ls', stderr=subprocess.STDOUT)



如果要将参数传递给命令,可以使用列表或使用调用shell并使用单个字符串。

output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)

使用a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE) ,您需要使用列表或使用shell=True ;

其中任何一种都可以。 前者是可取的。

a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)

a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)

此外,不应使用Popen.stdout.read / Popen.stderr.read ,而应使用Popen.stderr.read .communicate() (请参阅子流程文档以了解原因)。

proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
链接地址: http://www.djcxy.com/p/77143.html

上一篇: Pipe subprocess standard output to a variable

下一篇: Constantly print Subprocess output while process is running