如果我执行以下操作:
import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
我明白了:
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'
Run Code Online (Sandbox Code Playgroud)
显然,一个cStringIO.StringIO对象不能足够接近文件duck以适应subprocess.Popen.我该如何解决这个问题?
当执行Python文档中subprocess.run()给出的时,我得到一个TypeError:
>>> import subprocess
>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/subprocess.py", line 403, in run
with Popen(*popenargs, **kwargs) as process:
TypeError: __init__() got an unexpected keyword argument 'capture_output'
Run Code Online (Sandbox Code Playgroud)
我正在运行Python 3.6.6:
$ python3 --version
Python 3.6.6
Run Code Online (Sandbox Code Playgroud)