How to pass a string to subprocess.Popen in Python 2?

I would like to start a process from Python (2.4 / 2.5 / 2.6) using Popen, and I would like to give it a line as standard input.

I will write an example when a process executes "head -n 1" its input.

The following works, but I would like to solve this better without using echo:

>>> 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 suppose I can create a temporary file and write a line there - but this is also not very nice.

+3
source share
2 answers

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

Popen.communicate(input=my_input)

It works as follows:

p = subprocess.Popen(["head", "-n", "1"], stdin=subprocess.PIPE)
p.communicate('first\nsecond')

exit:

first

stdin subprocess.PIPE, .

+8

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
>>>
+5

Source: https://habr.com/ru/post/1717639/


All Articles