如何在 Python 2 中将字符串传递到 subprocess.Popen 中?
我想使用 Popen
从 Python (2.4/2.5/2.6) 运行一个进程,并且我 想要给它一个字符串作为它的标准输入。
我将编写一个示例,其中进程执行“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'
我想我可以创建一个临时文件并在那里写入字符串 - 但这也不是很好。
I would like to run a process from Python (2.4/2.5/2.6) using Popen
, and I
would like to give it a string as its standard input.
I'll write an example where the process does a "head -n 1" its input.
The following works, but I would like to solve it in a nicer way, without usingecho
:
>>> from subprocess import *
>>> p1 = Popen(["echo", "first line\nsecond line"], stdout=PIPE)
>>> Popen(["head", "-n", "1"], stdin=p1.stdout)
first line
I tried to use StringIO
, but it does not work:
>>> 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'
I guess I could make a temporary file and write the string there -- but that's not very nice either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过将字符串作为字符串提供给 communicate ?
它的工作原理如下:
输出:
当我第一次尝试时,我忘记将 stdin 设置为 subprocess.PIPE。
Have you tried to feed your string to communicate as a string?
It works like this:
output:
I forgot to set stdin to subprocess.PIPE when I tried it at first.
使用 os.pipe:
Use os.pipe: