How to capture all the output from a subprocess that *writes to stdin*?

Viewed 110

I want to use Python's subprocess.Popen to execute a child process, and collect all its output.

The problem is that the process in question writes not only to stdout and stderr, but sometimes also to stdin 1.

I want to capture all three of these output streams separately.

Naively, I tried this:

import subprocess

...

proc = subprocess.Popen(('/usr/bin/modulecmd', 'python', 'help', 'null'),
                        shell=False,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE,
                        stdin=subprocess.PIPE,)

stdout = proc.stdout.read()
stderr = proc.stderr.read()
stdin = proc.stdin.read()

proc.wait()

...but when the expression proc.stdin.read() is evaluated, an exception ensues (io.UnsupportedOperation: read).

Does anyone know how to use subprocess.Popen to handle this situation?

(BTW, I did try to implement a subclass of subprocess.Popen to support this use-case, but I kept running into errors similar to the one mentioned above. I just don't understands subprocess.Popen's internals well enough.)


1 See https://unix.stackexchange.com/a/667660/10618, as well as the comments therein, for a good discussion of this unusual behavior.

0 Answers
Related