mursuhaukka
mursuhaukka

Reputation: 65

Capturing all output from subprocess in python3

I want to capture all output into variables that subprocess prints out. Here is my code:

#!/usr/bin/env python3

import subprocess # Subprocess management
import sys # System-specific parameters and functions

try:
    args = ["svn", "info", "/directory/that/does/not/exist"]
    output = subprocess.check_output(args).decode("utf-8")
except subprocess.CalledProcessError as e:
    error = "CalledProcessError: %s" % str(e)
except:
    error = "except: %s" % str(sys.exc_info()[1])
else:
    pass

This script still prints this into the terminal:

svn: E155007: '/directory/that/does/not/exist' is not a working copy

How can I capture this into a variable?

Upvotes: 2

Views: 912

Answers (1)

Sekuraz
Sekuraz

Reputation: 588

check_output only captures stdout and NOT stderr (according to https://docs.python.org/3.6/library/subprocess.html#subprocess.check_output )

In order to capture stderr you should use

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT, ...)

I recommend reading the docs prior to asking here by the way.

Upvotes: 3

Related Questions