How do I save subprocess stderr to variable?

Question:

I am using the following code to run a subprocess. The command ‘cmd’ might at times fail and I wish to save the stderr output to a variable for further examination.

def exec_subprocess(cmd)
    with open('f.txt', 'w') as f:
        p = Popen(cmd, stderr=f)
        p.wait()

Right now as you can see I am saving stderr to file. I then later save the file content to a list using readlines() which seems inefficient. What I would like instead is something like:

def exec_subprocess(cmd)
    err = []
    p = Popen(cmd, stderr=err)
    p.wait()
    return err

How do I efficiently save stderr to list?

Asked By: finjasnappy

||

Answers:

The working should be similar to capturing the stdout, so I advice reading about that – I found this answer quite helpful.

Answered By: Sasszem

You should use:

p=Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
outs, errs = p.communicate()

if you want to assign the output of stderr to a variable.

Popen.communicate

using the subprocess module

Answered By: Regretful
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.