parent.py
:
import subprocess
import sys
p = subprocess.Popen([sys.executable, 'sub.py'], stdin=subprocess.PIPE)
p.stdin.write('foo') # not even a newline seems to be required for this to work, oddly
# p.stdin.flush() # optional; seems like not required
_, _ = p.communicate() # this is required--otherwise it just seems to block
sub.py
:
print raw_input()
Then running parent.py
outputs foo
as expected.
If you care about the return value of communicate()
, just replace _, _
with out, err
(or e.g. out, _
if you only care about the STDOUT); I just like to mark unused variables with _
, although one could simply completely ignore the return value of communicate()
... but then it would look like communicate
returns nothing.
See: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate
UPDATE:
Looks like you can also just:
p = subprocess.Popen([sys.executable, 'sub.py'], stdin=subprocess.PIPE)
_, _ = p.communicate(input='foo')