Redirect subprocess stderr to stdout

前端 未结 2 1804
说谎
说谎 2020-12-03 06:44

I want to redirect the stderr output of a subprocess to stdout. The constant STDOUT should do that, shouldn\'t it?

However,

$ python >/dev/null -c         


        
2条回答
  •  难免孤独
    2020-12-03 07:18

    Actually, using subprocess.STDOUT does exactly what is stated in the documentation: it redirects stderr to stdout so that e.g.

    proc = subprocess.Popen(self.task["command"], shell=False, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ""
    while (True):
        # Read line from stdout, break if EOF reached, append line to output
        line = proc.stdout.readline()
        line = line.decode()
        if (line == ""): break
        output += line
    

    results in variable output containing the process' output from both stdout and stderr.

    stderr=subprocess.STDOUT redirects all stderr output directly to stdout of the calling process, which is a major difference.

提交回复
热议问题