Grokbase Groups Python tutor May 2005

On Wed, 11 May 2005, Jeffrey Rice wrote:

I am having a little problem with how to pipe a variable's contents to an
external command. Essentially, I have a variable that contains the
contents of a variable that I want to feed to a series of external commands
(clamav and spamassassin).
Hi Jeffrey,

Ok, let's take a look.

CLAMAV_h= os.popen(CLAMAV, 'w')
Ah, ok. The value of the 'close()' here isn't defined, so you probably
won't get anything. Let me double check that:

import os
f = os.popen('ls')
result = f.close()
<type 'NoneType'>

Yeah, no value. By the way, we can also look this up by reading the
documentation on file-like objects:

Anyway, so trying to get a result from close() is a no-go. But when we
open up a process, we can get back both an "input" file and an "output
file". os.popen() just gives us the output stream, since unidirectional
communication is the common case. But there are variations of popen that
can give us both:

You're probably looking for 'popen2', which gives us both streams.
Here's an example with the word-counting Unix program 'wc':

child_out, child_in = popen2.popen2("wc")
child_in.write("hello world\nthis is a test\ngoodbye!\n")
result =
' 3 7 36\n'

Three lines, seven words, and thirty-six characters. Sounds right.

That being said, if you haven't used either popen2 or subprocess set, you
may want to try subprocess first, as there are some subtleties to using
popen2 that aren't obvious at first.

(Some of these subtleties are documented in:

The 'subprocess' module is described here:

and should be fairly easy to work with. I haven't yet installed Python
2.4 on my home machine, so I'll need to delegate to someone else on the
Tutor list here for a subprocess example. *grin*

If you have more questions, please feel free to ask!

Search Discussions

Discussion Posts


Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 2 of 5 | next ›
Discussion Overview
grouptutor @
postedMay 12, '05 at 4:39a
activeMay 16, '05 at 12:18a

2 users in discussion

Jeffrey Rice: 3 posts Danny Yoo: 2 posts



site design / logo © 2022 Grokbase