process.stdout.readline() hangs. How to use it properly?

后端 未结 3 1851
自闭症患者
自闭症患者 2020-12-21 02:59

I want to repeatedly send requests to process standard input and receive responses from standard output without calling subprocess mul

3条回答
  •  伪装坚强ぢ
    2020-12-21 03:23

    You need to use communicate to interact with your sub-process (https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate). Here is an updated version of your main code:

    import subprocess
    p = subprocess.Popen(['python','subproc.py'],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
    
    while True:
        s = raw_input('Enter message:')
        response, _ = p.communicate(s)
        if response!= '':
            print "Process response:", response
        else:
            break
    

    You also have to be careful that while you have a loop in your main code your subproc code only runs once. Only the first iteration will correctly receive a response the second communicate call will raise an exception as the stdin file of the subprocess will be closed by then.

提交回复
热议问题