Using subprocess with select and pty hangs when capturing output

前端 未结 4 1249
说谎
说谎 2021-01-31 12:41

I\'m trying to write a python program that is able to interact with other programs. That means sending stdin and receiving stdout data. I cannot use pexpect (although it definit

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 13:13

    From what I understand, you do not need to use pty. runner.py can be modified as

    import subprocess
    import sys
    
    def main():
            process = subprocess.Popen(['python', 'outputter.py'],
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
            while process.poll() is None:
                    output = process.stdout.readline()
                    sys.stdout.write(output)
                    sys.stdout.flush()
            print "**ALL COMPLETED**"
    
    if __name__ == '__main__':
            main()
    

    process.stdout.read(1) can be used instead of process.stdout.readline() for real-time output per character from the subprocess.

    Note: If you do not require real-time output from the subprocess, use Popen.communicate to avoid the polling loop.

提交回复
热议问题