How do I stream a subprocess's stderr while returning stdout as string?

Solution 1:

If you read the documentation, you'll note that capture_output is not what you want:

If capture_output is true, stdout and stderr will be captured.

If you want to capture stdout but not stderr, just set stdout=subprocess.PIPE. If I have a script named script.sh that contains:

#!/bin/sh

echo "This is normal output"
echo "This is an error" >&2

I can capture the output like this:

>>> res = subprocess.run(['sh', 'script.sh'], stdout=subprocess.PIPE)
This is an error
>>> res.stdout
b'This is normal output\n'

Output on stderr showed up on the console, while output to stdout was captured in res.stdout.