如果我执行以下操作:

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对象没有足够接近文件duck以适应subprocess.Popen。我该如何解决这个问题?

有帮助吗?

解决方案

Popen.communicate() 文档:

  

请注意,如果要将数据发送到   你需要的过程&#st; s stdin   用它创建Popen对象   标准输入=管道。同样,得到任何东西   除了结果元组中的None之外,   你需要给stdout = PIPE和/或   stderr = PIPE。

     

取代os.popen *

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

警告使用communic()而不是   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版本中,您可以使用 子流程.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
# -> 

其他提示

我想出了这个解决方法:

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

有更好的吗?

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

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

subprocess.check_call(['your-command'], stdin=read)

如果您使用的是Python 3.4或更高版本,那么这是一个美丽的解决方案。使用 input 参数而不是 stdin 参数,该参数接受一个bytes参数:

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

我正在使用python3并发现你需要对你的字符串进行编码才能将它传递给stdin:

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)

&quot;显然cStringIO.StringIO对象没有足够接近文件duck以适应subprocess.Popen&quot;

: - )

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

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

请注意,如果 s 太大, Popen.communicate(input = s)会给你带来麻烦,因为显然父进程会在之前缓冲它 / em>分叉子子进程,意味着它需要“两倍多”的时间。此时使用的内存(至少根据“引擎盖下”解释和此处的链接文档)。在我的特定情况下, s 是一个首先完全展开的生成器,然后才写入 stdin ,因此父进程在生成子进程之前很大, 并没有留下任何记忆来分叉它:

文件&quot; /opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py",第1130行,在_execute_child中     self.pid = os.fork() OSError:[Errno 12]无法分配内存

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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top