如果我执行以下操作:
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的要求。我该如何解决这个问题?
call(['ls', '-1'], shell=True)
是错误的。我建议阅读subprocess标签描述中的常见问题。特别是为什么使用参数为序列时,subprocess.Popen不起作用? 解释了为什么call(['ls', '-1'], shell=True)
是错误的。我记得在博客文章下留过评论,但出于某种原因现在找不到它们了。 - jfssubprocess.run
,网址为https://dev59.com/MFYM5IYBdhLWcg3wgwXH#59496029 - user3064538