hcs42 hcs42 - 2 years ago 81
Python Question

How do I pass a string into subprocess.Popen in Python 2?

I would like to run a process from Python (2.4/2.5/2.6) using

, 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 using

>>> 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
, 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.

Answer Source

Have you tried to feed your string to communicate as a string?


It works like this:

p = subprocess.Popen(["head", "-n", "1"], stdin=subprocess.PIPE)



I forgot to set stdin to subprocess.PIPE when I tried it at first.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download