Search code examples
pythonsubprocess

Python subprocess communicate kills my process


Why does communicate kill my process? I want an interactive process but communicate does something so that I cannot take raw_input any more in my process.

from sys import stdin 
from threading import Thread
from time import sleep

if __name__ == '__main__':
    print("Still Running\n")
    x = raw_input()    
    i = 0
    while ('n' not in x ) :
        print("Still Running " + str(i) + " \r\n")
        x = raw_input()
        i += 1

    print("quit")



print(aSubProc.theProcess.communicate('y'))
print(aSubProc.theProcess.communicate('y'))

exception!

self.stdin.write(input)
ValueError: I/O operation on closed file

Solution

  • 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()