subprocess.Popen() IO redirect

前端 未结 2 1562
旧巷少年郎
旧巷少年郎 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:45

    Output redirection with ">" is a feature of shells - by default, subprocess.Popen doesn't instantiate one. This should work:

    server = subprocess.Popen(args, shell=True)
    
    0 讨论(0)
  • 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.

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