Hide
Bored? Check out the Recent Activity on Siafoo Join Siafoo Now or Learn More

Redirecting stdout for a spawned process Atom Feed 0

In Brief Redirect stdin/stdout/stderr after launching a process using Python's subprocess module.... more
# 's
 1from subprocess import Popen, PIPE
2
3proc = Popen(['find', '.'], stdout=PIPE, stderr=PIPE, stdin=PIPE)
4
5stdout, stderr = proc.communicate()
6
7for l in stdout.split('\n'):
8 print l
9
10# One way to filter output and add colors (in this case, the PostgreSQL's psql program)
11#for line in stderr.split('\n'):
12# print line.replace('ERROR', '\033[1;31mERROR\033[1;m')\
13# .replace('NOTICE', '\033[1;34mNOTICE\033[1;m')\
14# .replace('WARNING', '\033[1;31mWARNING\033[1;m')

Redirect stdin/stdout/stderr after launching a process using Python's subprocess module.

This is useful for suppressing, logging, or filtering the output. The commented out section of the code will make the ERROR, NOTICE, WARNING labels on psql output colored red, blue and yellow respectively.

Comments

over 7 years ago (22 Jan 2009 at 10:03 AM) by David Isaacson
Ah I was trying to figure out how to do this the other day. Sweet.
over 7 years ago (07 Nov 2009 at 05:41 PM) by xanadu
This wasn't exactly what I was looking for, but I'm sure it'll come in handy some time, so I bookmarked your article at del.icio.us. Thanks