如果我做到以下幾點: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。我如何解決這個問題?
相反的爭議我這個被刪除,我將它作爲一個評論...推薦閱讀答案:道格樂門的Python子週期博客文章模塊](http://www.doughellmann.com/PyMOTW/subprocess/)。 – 2013-06-18 22:43:25
博客文章包含多個錯誤,例如[第一個代碼示例:`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