Python Subprocess Communicate Kills My Process
Solution 1:
communicate
and wait
methods of Popen
objects, close the PIPE
after the process returns. If you want stay in communication with the process try something like this:
import subprocess
proc = subprocess.Popen("some_process", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
proc.stdin.write("input")
proc.stdout.readline()
Solution 2:
Why does communicate kill my process?
From the docs for Popen.communicate(input=None, timeout=None)
:
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.
You may call .communicate()
only once. It means that you should provide all input at once:
#!/usr/bin/env pythonimport os
import sys
from subprocess import Popen, PIPE
p = Popen([sys.executable, 'child.py'], stdin=PIPE, stdout=PIPE)
print p.communicate(os.linesep.join('yyn'))[0]
Output
Still Running
Still Running0
Still Running1
quit
Notice the doubled newlines: one from '\r\n'
and another from print
statement itself in your script for the child process.
Output shows that the child process received three input lines successfully ('y'
, 'y'
, and 'n'
).
Here's a similar code using subprocess.check_output()
's input
parameter from Python3.4:
#!/usr/bin/env python3.4import os
import sys
from subprocess import check_output
output = check_output(['python2', 'child.py'], universal_newlines=True,
input='\n'.join('yyn'))
print(output, end='')
It produces the same output.
If you want to provide a different input depending on responses from the child processes then use pexpect
module or its analogs to avoid issues mentioned in Why not just use a pipe (popen())?
Post a Comment for "Python Subprocess Communicate Kills My Process"