系统相关
首页 > 系统相关> > python – 管道子进程标准输出到变量

python – 管道子进程标准输出到变量

作者:互联网

参见英文答案 > Store output of subprocess.Popen call in a string                                    10个
我想使用子进程模块在pythong中运行命令,并将输出存储在变量中.但是,我不希望将命令的输出打印到终端.
对于此代码:

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

我在终端中获取目录列表,而不是将其存储在.我也尝试过:

 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-6,python,pipe,subprocess
来源: https://codeday.me/bug/20190916/1806600.html