os.shell, recursion, encryption

Will Ware wware at world.std.com
Mon Feb 14 15:44:45 EST 2000


55555 (55555 at dakotacom.net) wrote:
: How does os.popen work?  I'm afraid that I don't understand pipes.

Caveat: I'm a Unix guy, pretty clueless about Windows, and this may
all be Unix-ish stuff.

When you open a file for reading, the file becomes a source of bytes.
You read the bytes in sequence and there is some testable condition
to tell you when there are no more bytes. Since many files are text,
it's often convenient to take the bytes in lines. So you often see
idioms like this:

f = open('somefile')
for L in f.readlines():
	.... do something with L ....
f.close()

or more tersely:

for L in open('somefile').readliines():
	.... do something with L ....

In this latter case, the opened file should automatically be closed
when it gets garbage-collected. (Whether that happens, or the
conditions under which it might not, is another question for subtler
minds than mine.)

In Unix, many programs (particularly ones that operate on text) are
written to look like filters, meaning that they accept a stream of
bytes from elsewhere and produce a stream of bytes that can go to
yet somewhere else. Each such program has "standard input" and
"standard output". Output from one program can be directed to the
input of another, and hence the term "pipe", just like in plumbing.
So you see constructs like this:
   filter1 < infile | filter2 | filter3 | filter4 > outfile
And this means that the contents of 'infile' are run thru all four
filters in succession, and the results end up in 'outfile'.

Python, too, can accept input from a chain of filters, so I can
type something like this:

p = os.popen('filter1 < infile | filter2 | filter3 | filter4')
for L in p.readlines():
	... do stuff with L ...
p.close()

and this means that I want, as input, the stuff that would have
been dumped into 'outfile' in the earlier example.

Sorry if this seems circuitous and long-winded (and I'm _really_
sorry if none of this is meaningful in the Windows world), but this
saves you the hassle of creating a bunch of intermediate files to
catch the output at each stage in the pipeline. (Essentially Unix
is creating those files itself and keeping track of them without
bothering you with the details, and they all disappear when you're
finished.)

I suspect Python would also be happy with an output pipe, something
where you'd be writing to the front of a pipeline like this:

p = os.popen('filter1 | filter2 | filter3 | filter4 > outfile', 'w')
for <some loop>:
	...
	p.write(....)
p.close()

but I've never myself written that, that I can recall.

-- 
-- I can picture in my mind a world without war, a world without hate. And --
-- I can picture us attacking that world, because they'd never expect it.  --
Will Ware - N1IBT - wware at world.std.com



More information about the Python-list mailing list