Program getting stuck when using subprocess.Popen() or subprocess.check_call()

前端 未结 2 1901
独厮守ぢ
独厮守ぢ 2021-01-24 11:08

I want to run a program from python and find its memory usage. To do so I am using:

l=[\'./a.out\',\'<\',\'in.txt\',\'>\',\'out.txt\']
p=subprocess.Popen(l         


        
2条回答
  •  终归单人心
    2021-01-24 11:39

    There are two issues (at least):

    1. <, > redirection is handled by a shell. subprocess doesn't spawn a shell by default (you shouldn't either)
    2. If stdout=PIPE, stderr=PIPE then you must read from the pipes otherwise the process may block forever

    To make a subprocess read from a file and write to a file:

    from subprocess import check_call, STDOUT
    
    with open('in.txt') as file, open('out.txt', 'w') as outfile:
        check_call(["./a.out"], stdin=file, stdout=outfile, stderr=STDOUT)
    

    stderr=STDOUT merges stdout, stderr.

提交回复
热议问题