如果我这样做:

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。我怎么解决这个问题呢?


当前回答

在Python 3.7+上这样做:

my_data = "whatever you want\nshould match this f"
subprocess.run(["grep", "f"], text=True, input=my_data)

并且您可能希望添加capture_output=True以获得以字符串形式运行命令的输出。

在旧版本的Python中,将text=True替换为universal_newlines=True:

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)

其他回答

我想出了一个变通办法:

>>> 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()

还有更好的吗?

Beware that Popen.communicate(input=s)may give you trouble ifsis too big, because apparently the parent process will buffer it before forking the child subprocess, meaning it needs "twice as much" used memory at that point (at least according to the "under the hood" explanation and linked documentation found here). In my particular case,swas a generator that was first fully expanded and only then written tostdin so the parent process was huge right before the child was spawned, and no memory was left to fork it:

文件“/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py”,第1130行,在_execute_child中 自我。Pid = os.fork() OSError: [Errno 12]不能分配内存

在Python 3.7+上这样做:

my_data = "whatever you want\nshould match this f"
subprocess.run(["grep", "f"], text=True, input=my_data)

并且您可能希望添加capture_output=True以获得以字符串形式运行命令的输出。

在旧版本的Python中,将text=True替换为universal_newlines=True:

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)

显然是cStringIO。StringIO对象的嘎嘎声不够接近 适合子进程的文件鸭。Popen

恐怕不行。管道是一个低级的操作系统概念,因此它绝对需要一个由操作系统级文件描述符表示的文件对象。你的解决方法是正确的。

"""
Ex: Dialog (2-way) with a Popen()
"""

p = subprocess.Popen('Your Command Here',
                 stdout=subprocess.PIPE,
                 stderr=subprocess.STDOUT,
                 stdin=PIPE,
                 shell=True,
                 bufsize=0)
p.stdin.write('START\n')
out = p.stdout.readline()
while out:
  line = out
  line = line.rstrip("\n")

  if "WHATEVER1" in line:
      pr = 1
      p.stdin.write('DO 1\n')
      out = p.stdout.readline()
      continue

  if "WHATEVER2" in line:
      pr = 2
      p.stdin.write('DO 2\n')
      out = p.stdout.readline()
      continue
"""
..........
"""

out = p.stdout.readline()

p.wait()