如何将字符串传递给subprocess.Popen(使用stdin参数)?

348 投票
12 回答
438948 浏览
提问于 2025-04-11 09:27

如果我这样做:

import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]

我得到:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
    (p2cread, p2cwrite,
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'

显然,cStringIO.StringIO 这个对象在某些方面不够像文件,所以 subprocess.Popen 不能正常使用。那我该怎么解决这个问题呢?

12 个回答

42

如果你使用的是Python 3.4或更高版本,有一个很不错的解决办法。你可以用input这个参数,代替stdin参数,它可以接受字节类型的输入:

output_bytes = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input=b"foo",
)

这个方法适用于check_outputrun,但是不适用于call或者check_call,原因不太清楚。

在Python 3.7及以上版本中,你还可以加上text=True,这样check_output就可以接受字符串作为输入,并返回字符串(而不是字节类型):

output_string = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input="foo",
    text=True,
)
50

我找到了一个解决方法:

>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()

有没有更好的方法呢?

397

Popen.communicate() 的说明:

注意,如果你想要向进程的输入(stdin)发送数据,你需要在创建 Popen 对象时加上 stdin=PIPE。同样,如果你想在结果中得到除了 None 以外的内容,你也需要设置 stdout=PIPE 和/或 stderr=PIPE。

替代 os.popen*

    pipe = os.popen(cmd, 'w', bufsize)
    # ==>
    pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin

警告 使用 communicate() 而不是 stdin.write()、stdout.read() 或 stderr.read(),这样可以避免因为其他操作系统管道的缓冲区满了而导致的死锁,进而阻塞子进程。

所以你的例子可以这样写:

from subprocess import Popen, PIPE, STDOUT

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->

在 Python 3.5 及以上版本(3.6 及以上版本支持 encoding),你可以使用 subprocess.run,通过一次调用将输入作为字符串传递给外部命令,并获取它的退出状态和输出字符串:

#!/usr/bin/env python3
from subprocess import run, PIPE

p = run(['grep', 'f'], stdout=PIPE,
        input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
# -> four
# -> five
# -> 

撰写回答