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

最佳答案

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

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

命令cdrecord --help 输出到stderr,所以你需要用管道代替。您还应该像我在下面所做的那样将命令分解为 token 列表,或者替代方法是传递 shell=True 参数,但这会启动一个成熟的外壳,这可能很危险如果你不控制命令字符串的内容。

>>> 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 #.
...

https://stackoverflow.com/questions/4514751/

相关文章:

python - SQLAlchemy:如何过滤日期字段?

python - 有效地检查 Python/numpy/pandas 中的任意对象是否为 NaN?

python - 断言 numpy.array 相等性的最佳方法?

python - 在系统范围内安装 pip 和 virtualenv 的官方 "preferred"

python - 如何从具有透明背景的 matplotlib 导出绘图?

python - matplotlib 中的曲面图

python - 如何在 Tesseract 和 OpenCV 之间进行选择?

python - 在 TensorFlow 中使用预训练的词嵌入(word2vec 或 Glove)

python - sqlite3.ProgrammingError : You must not u

python - Python 多处理模块的 .join() 方法到底在做什么?