2008-10-02 68 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", 
) 
相關問題