Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I save subprocess stderr to 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading