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?
Answers:
The working should be similar to capturing the stdout
, so I advice reading about that – I found this answer quite helpful.
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.
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?
The working should be similar to capturing the stdout
, so I advice reading about that – I found this answer quite helpful.
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.