1

How can I implement something like

$ echo "hello" | my_app

with usage of Python's subprocess?

subprocess.Popen() expects a pipe or a file handle for STDIN. But I want to provide STDIN for the called program via a variable. So something like

myinput = "hello"
subprocess.Popen("an_external_programm", stdin=myinput)
….
frlan
  • 6,950
  • 3
  • 31
  • 72
  • 1
    Have a look at `Popen.communicate()`. Link: https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate – elParaguayo May 31 '16 at 15:56
  • Can you be clear about your use case? First off you look like you're piping "hello" to your script, in the second example it's a variable in your script. – elParaguayo May 31 '16 at 15:59
  • I want to call an external tool from inside my Python script in the kind of the shell example but the content -- the "hello" from shell sxample, is coming from a Python variable. – frlan May 31 '16 at 16:35
  • Actually Popen.communicate() did the trick – frlan Jun 01 '16 at 06:59

2 Answers2

1

I was able to solve my problem by using Popen.communicate()

So some kind of pseudo code:

proc = subprocess.Popen(…)
proc.communicate(input="my_input_via_stdin")
frlan
  • 6,950
  • 3
  • 31
  • 72
0

In a python script named myscript.py

import sys

for line in sys.stdin:
     print(line)

in unix

echo 'hello' | myscript.py

Seekheart
  • 1,135
  • 7
  • 8