Starting and Controlling an External Process via STDIN/STDOUT with Python

后端 未结 2 1659
猫巷女王i
猫巷女王i 2021-01-13 07:12

I need to launch an external process that is to be controlled via messages sent back and forth via stdin and stdout. Using subprocess.Popen I am able to start the process b

相关标签:
2条回答
  • 2021-01-13 07:54

    process.communicate(input='\n') is wrong. If you will notice from the Python docs, it writes your string to the stdin of the child, then reads all output from the child until the child exits. From doc.python.org:

    Popen.communicate(input=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. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

    Instead, you want to just write to the stdin of the child. Then read from it in your loop.

    Something more like:

    process=subprocess.Popen([PathToProcess],stdin=subprocess.PIPE,stdout=subprocess.PIPE);
    for i in xrange(StepsToComplete):
        print "Forcing step # %s"%i
        process.stdin.write("\n")
        result=process.stdout.readline()
    

    This will do something more like what you want.

    0 讨论(0)
  • 2021-01-13 08:11

    You could use Twisted, by using reactor.spawnProcess and LineReceiver.

    0 讨论(0)
提交回复
热议问题