subprocess.Popen() IO redirect

前端 未结 2 1573
旧巷少年郎
旧巷少年郎 2020-12-03 11:20

Trying to redirect a subprocess\' output to a file.

server.py:

while 1:
    print \"Count \" + str(count)
    sys.stdout.flush()
    count = count +          


        
2条回答
  •  生来不讨喜
    2020-12-03 11:58

    Altenatively, you can use the stdout parameter with a file object:

    with open('temp.txt', 'w') as output:
        server = subprocess.Popen('./server.py', stdout=output)
        server.communicate()
    

    As explained in the documentation:

    stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.

提交回复
热议问题