321

如果我执行以下操作:

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。我该如何解决这个问题?

4

12 回答 12

377

Popen.communicate()文档:

请注意,如果您想将数据发送到进程的标准输入,您需要使用标准输入=PIPE 创建 Popen 对象。同样,要在结果元组中获得除 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() 以避免由于任何其他OS 管道缓冲区填满并阻塞子进程而导致的死锁。

所以你的例子可以写成如下:

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+ for 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
# -> 
于 2008-10-03T04:11:07.493 回答
48

我想出了这个解决方法:

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

有更好的吗?

于 2008-10-02T17:27:55.760 回答
29

如果您使用的是 Python 3.4 或更高版本,那么有一个很好的解决方案。使用input参数而不是stdin接受字节参数的参数:

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

这适用于check_outputand run,但不适用于callorcheck_call出于某种原因。

在 Python 3.7+ 中,您还可以添加text=Truemakecheck_output将字符串作为输入并返回字符串(而不是bytes):

output_string = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input="foo",
    text=True,
)
于 2016-12-08T10:04:26.587 回答
27

我有点惊讶没有人建议创建管道,在我看来,这是将字符串传递给子进程的标准输入的最简单的方法:

read, write = os.pipe()
os.write(write, "stdin input here")
os.close(write)

subprocess.check_call(['your-command'], stdin=read)
于 2015-11-02T16:34:03.423 回答
13

我正在使用 python3 并发现您需要先对字符串进行编码,然后才能将其传递到标准输入:

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n'.encode())
print(out)
于 2014-07-27T15:29:17.287 回答
12

显然 cStringIO.StringIO 对象与文件鸭子不够接近以适应 subprocess.Popen

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

于 2008-10-02T18:33:23.153 回答
10
from subprocess import Popen, PIPE
from tempfile import SpooledTemporaryFile as tempfile
f = tempfile()
f.write('one\ntwo\nthree\nfour\nfive\nsix\n')
f.seek(0)
print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()
f.close()
于 2012-04-13T03:36:37.190 回答
7
"""
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()
于 2013-06-14T13:20:23.007 回答
7

在 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=Trueuniversal_newlines=True

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)
于 2019-12-27T04:29:04.120 回答
5

请注意,如果太大,Popen.communicate(input=s)可能会给您带来麻烦,因为显然父进程会在分叉子子进程之前对其进行缓冲,这意味着它需要“两倍”的已用内存(至少根据“引擎盖下”的解释)并在此处找到链接文档)。在我的特殊情况下,是一个生成器,它首先完全扩展,然后才写入,因此在子进程生成之前父进程非常大,并且没有内存可以分叉它:ssstdin

File "/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py", line 1130, in _execute_child self.pid = os.fork() OSError: [Errno 12] Cannot allocate memory

于 2014-05-19T14:56:38.567 回答
2

这对我来说太过分了grep,但是通过我的旅程,我了解了 Linux 命令expect和 python 库pexpect

  • expect : 与交互式程序的对话
  • pexpect:用于生成子应用程序的 Python 模块;控制它们;并响应其输出中的预期模式。
import pexpect
child = pexpect.spawn('grep f', timeout=10)
child.sendline('text to match')
print(child.before)

使用像pexpect这样的交互式 shell 应用程序ftp是微不足道的

import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before   # Print the result of the ls command.
child.interact()     # Give control of the child to the user.
于 2021-03-22T21:35:46.237 回答
1
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
p.stdin.write('one\n')
time.sleep(0.5)
p.stdin.write('two\n')
time.sleep(0.5)
p.stdin.write('three\n')
time.sleep(0.5)
testresult = p.communicate()[0]
time.sleep(0.5)
print(testresult)
于 2009-04-09T04:39:40.930 回答