Custom Formatting The Output Of subprocess.Popen
Diez B. Roggisch
deets at nospam.web.de
Fri Nov 21 10:58:04 EST 2008
thedsadude at gmail.com wrote:
> Hello,
>
> I'm launching a script as follows:
> <code>
> p = subprocess.Popen(['./p.py', 'aa'])
>
> p.wait()
> </code>
>
> If p.py writes to sys.stdout, then it is shown on the console.
> Looking at the console, then, it is hard to distinguish the output of
> p.py from that of the script launching it. I'd like to do it so the
> output looks like this:
> <output>
> output of launcher
> p: output of launchee
> p: more output of launchee
> more output of launcher
> </output>
> i.e., that each output line of p.py will be formatted so that it is
> preceded by 'p:'.
>
> How should this be done, then? Should I write a file class, and pass
> on object like so:
> <code>
> custom_f = custom_file(sys.stdout, line_prefix = 'p')
>
> p = subprocess.Popen(['./p.py', 'aa'], stdout = custom_f)
>
> p.wait()
> </code>
> or is a different option easier? Are there any links for writing
> custom file classes?
Why can't you just do?
print "<output>"
p = subprocess.Popen(...)
p.wait()
print "</output>"
? If you wait for the subprocess to terminate anyway..
Another way would be to use the p.communicate()-call to get the child's
output, and print that to stdout yourself, pre/postfixing it as needed.
Diez
More information about the Python-list
mailing list