Grokbase Groups Python tutor May 2005
FAQ

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')
CLAMAV_h.write(EMAIL)
CLAM_RESULT=CLAMAV_h.close()
print CLAM_RESULT
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(result)
<type 'NoneType'>
######


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

http://www.python.org/doc/lib/bltin-file-objects.html


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:

http://www.python.org/doc/lib/module-popen2.html

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")
child_in.close()
result = child_out.read()
child_out.close()
result
' 3 7 36\n'
######

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


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:
http://www.python.org/doc/lib/popen2-flow-control.html)

The 'subprocess' module is described here:

http://www.python.org/doc/lib/module-subprocess.html

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

Previous

Follow ups

Related Discussions

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

2 users in discussion

Jeffrey Rice: 3 posts Danny Yoo: 2 posts

People

Translate

site design / logo © 2022 Grokbase