小编典典

管道子流程标准输出到变量

python

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

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

阅读 179

收藏
2021-01-20

共1个答案

小编典典

要获取输出ls,请使用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,如果您不控制命令的内容,可能会很危险。命令字符串。

>>> 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 #.
...
2021-01-20