Parsing stdout through a pipe?

Noah noah at
Sun Jul 13 15:25:15 CEST 2003

"MK" <MK at> wrote in message news:<bepf5g$7u6st$1 at>...
> I have a Win32 console application (SNMPUTIL.EXE) which listens
> to incoming SNMP messages:
> C:\>snmputil trap
> snmputil: listening for traps...
> ...
> I'd like to write a Python application which would intercept/parse this
> stdout
> output, and invoke various pop-ups ("alarms"). Any ideas?

You can use popen and friends to create a pipe to listen to the output
of an external application, but there are many pitfalls to using a 
simple pipe to control an external application.

Do you need to respond to the output by writing message back through stdin?
If yes, then pipes are a bad way to go. Does snmptrap print events continuously
(versus printing just a single trap even and then exiting)? 
If it runs continuously then a pipe is a bad way to go.
The reason these scenarios are bad has to do with way the stdio buffers pipes.
Stdio will not necessarily flush the output buffer after snmptrap prints
some data. Stdio will flush the buffer when full, not after data is printed.
So your snmptrap may print some data, but it will just sit in the buffer
until snmptrap prints more data to fill it the buffer. There is no way for you
to force the buffer to flush.

The way around this is to use UNIX where you can use a pseudo TTY :-)
You can also use Cygwin... I am not sure if there is an ideal solution
under Windows. Cygwin manages to implement a pseduo TTY system on Windows, so
there must be some sort of solution using the win32 API.

I have a pseudo TTY wrapper library called pexpect here:
It works pretty well under Cygwin Python, but not under regular Windows python.

On the other hand if your snmptrap program just prints one event and then
exits then you can use pipes because the buffer will be flushed when
snmptrap exits. Or, if you can modify the source to snmptrap then you can
have it force a flush on stdout after each print.


More information about the Python-list mailing list