如果我做到以下几点: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