0

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?

  • 1
    You should look at https://stackoverflow.com/questions/31833897/python-read-from-subprocess-stdout-and-stderr-separately-while-preserving-order – GoWiser Aug 09 '22 at 08:41
  • Does this answer your question? [Python read from subprocess stdout and stderr separately while preserving order](https://stackoverflow.com/questions/31833897/python-read-from-subprocess-stdout-and-stderr-separately-while-preserving-order) – GoWiser Aug 09 '22 at 08:41
  • I suggest taking look at [subprocess.Popen.communicate](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate) – Daweo Aug 09 '22 at 08:53
  • [Subprocess stderr to variable.](https://stackoverflow.com/a/16198668) – attilasomogyi Aug 09 '22 at 09:06
  • The working should be similar to capturing the `stdout`, so I advice reading about that - I found [this answer](https://stackoverflow.com/a/4760517/4379569) quite helpful. – Uncle Dino Aug 09 '22 at 08:41

1 Answers1

1

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

Regretful
  • 336
  • 2
  • 10