如何在Python 2中将字符串传递给subprocess.Popen?
我想在Python(2.4/2.5/2.6)中使用Popen
来运行一个进程,并且想给它一个字符串作为标准输入。
我会写一个例子,让这个进程对它的输入执行“head -n 1”的操作。
下面这个方法可以用,但我想找一个更好的办法,不想使用echo
:
>>> from subprocess import *
>>> p1 = Popen(["echo", "first line\nsecond line"], stdout=PIPE)
>>> Popen(["head", "-n", "1"], stdin=p1.stdout)
first line
我试着用StringIO
,但是不管用:
>>> from StringIO import StringIO
>>> Popen(["head", "-n", "1"], stdin=StringIO("first line\nsecond line"))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/usr/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: StringIO instance has no attribute 'fileno'
我想我可以创建一个临时文件,把字符串写进去——不过这也不是个好办法。
2 个回答
5
使用 os.pipe:
>>> from subprocess import Popen
>>> import os, sys
>>> read, write = os.pipe()
>>> p = Popen(["head", "-n", "1"], stdin=read, stdout=sys.stdout)
>>> byteswritten = os.write(write, "foo bar\n")
foo bar
>>>
8
你有没有试过把你的字符串直接传给 communicate 呢?
Popen.communicate(input=my_input)
它的用法是这样的:
p = subprocess.Popen(["head", "-n", "1"], stdin=subprocess.PIPE)
p.communicate('first\nsecond')
输出:
first
我第一次尝试的时候忘了把 stdin 设置为 subprocess.PIPE。