【发布时间】:2010-09-14 21:07:52
【问题描述】:
如果我执行以下操作:
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。我该如何解决这个问题?
【问题讨论】:
-
我没有对我的答案提出异议,而是将其作为评论添加...推荐阅读:Doug Hellmann's Python Module of the Week blog post on subprocess。
-
博文包含多个错误,例如,the very first code example:
call(['ls', '-1'], shell=True)不正确。我建议改为阅读common questions from subprocess' tag description。特别是,Why subprocess.Popen doesn't work when args is sequence? 解释了为什么call(['ls', '-1'], shell=True)是错误的。我记得在博文下留下了 cmets,但由于某种原因我现在看不到它们。 -
对于较新的
subprocess.run,请参阅stackoverflow.com/questions/48752152/…
标签: python subprocess stdin