I would like to direct a python script's subprocess' stdout and stdin into the same file. What I don't know is how to make the lines from the two sources distinguishable? (For example prefix the lines from stderr with an exclamation mark.)
In my particular case there is no need for live monitoring of the subprocess, the executing Python script can wait for the end of its execution.
At the moment all other answers don't handle buffering on the child subprocess' side if the subprocess is not a Python script that accepts
-u
flag. See "Q: Why not just use a pipe (popen())?" in the pexpect documentation.To simulate
-u
flag for some of C stdio-based (FILE*
) programs you could trystdbuf
.If you ignore this then your output won't be properly interleaved and might look like:
You could try it with the following client program, notice the difference with/without
-u
flag (['stdbuf', '-o', 'L', 'child_program']
also fixes the output):On Linux you could use
pty
to get the same behavior as when the subprocess runs interactively e.g., here's a modified @T.Rojan's answer:It assumes that stderr is always unbuffered/line-buffered and stdout is line-buffered in an interactive mode. Only full lines are read. The program might block if there are non-terminated lines in the output.
subprocess.STDOUT
is a special flag that tells subprocess to route all stderr output to stdout, thus combining your two streams.btw, select doesn't have a poll() in windows. subprocess only uses the file handle number, and doesn't call your file output object's write method.
to capture the output, do something like:
I suggest you write your own handlers, something like (not tested, I hope you catch the idea):
I found myself having to tackle this problem recently, and it took a while to get something I felt worked correctly in most cases, so here it is! (It also has the nice side effect of processing the output via a python logger, which I've noticed is another common question here on Stackoverflow).
Here is the code:
Here is the output:
You can replace the subprocess call to do whatever you want, I just chose running python with a command that I knew would print to both stdout and stderr. The key bit is reading stderr and stdout each in a separate thread. Otherwise you may be blocking on reading one while there is data ready to be read on the other.
If you want to interleave to get roughly the same order that you would if you ran the process interactively then you need to do what the shell does and poll stdin/stdout and write in the order that they poll.
Here's some code that does something along the lines of what you want - in this case sending the stdout/stderr to a logger info/error streams.
You may write the stdout/err to a file after the command execution. In the example below I use pickling so I am sure I will be able to read without any particular parsing to differentiate between the stdout/err and at some point I could dumo the exitcode and the command itself.