2008-10-02 70 views
221

如果我做到以下几点:Python - 如何将字符串传递到subprocess.Popen(使用stdin参数)?

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

+3

相反的争议我这个被删除,我将它作为一个评论...推荐阅读答案:道格乐门的Python子周期博客文章模块](http://www.doughellmann.com/PyMOTW/subprocess/)。 – 2013-06-18 22:43:25

+3

博客文章包含多个错误,例如[第一个代码示例:`call(['ls','-1'],shell = True)`](http://www.doughellmann.com/PyMOTW/subprocess /) 是不正确的。我建议阅读[subprocess'tag description](http://stackoverflow.com/tags/subprocess/info)中的常见问题。特别是,当args是序列时,为什么subprocess.Popen不工作?](http://stackoverflow.com/q/2400878/4279)解释了为什么`call(['ls','-1'],shell =真)`是错的。我记得在博客文章下发表评论,但由于某种原因我现在没有看到他们。 – jfs 2016-03-17 14:24:50

回答

248

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 

警告使用通信(),而不是 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版本,你可以使用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 
# -> 
+3

我错过了这个警告。我很高兴我问(即使我认为我有答案)。 – 2008-10-03 16:02:02

34

我想通了以下解决方法:

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

是否还有更好的吗?

+6

这不是一种解决方法 - 这是做到这一点的正确方法! – Moe 2008-10-02 18:10:46

+17

@Moe:不鼓励使用stdin.write(),使用p.communicate()。看到我的答案。 – jfs 2008-10-03 14:26:34

+8

根据子流程文档: 警告 - 使用通讯()而不是.stdin.write,.stdout.read或.stderr.read以避免由于任何其他OS管道缓冲区填满和阻止子进程而导致死锁。 – 2010-08-25 20:49:46

12

“显然,一个cStringIO.StringIO对象不呱足够接近到一个文件中的鸭子,以满足subprocess.Popen”

:-)

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

2
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) 
9
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() 
6
""" 
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() 
5

谨防Popen.communicate(input=s)可能会给你带来麻烦,如果s太大,因为很明显的父进程将缓冲它之前分叉子子,这意味着它需要“两倍”使用的内存在这一点上(至少根据“引擎盖下”的解释和链接文档发现here)。在我的具体情况,s是发电机,其最早是完全展开,然后才写入stdin所以父进程是孩子催生之前巨大的权利, 和无记忆留到餐桌吧:

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

14

我使用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) 
17

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

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

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

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

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