Re: Slinging OS commands arround like Perl.

Tim Peters (tim@ksr.com)
Sat, 26 Feb 94 22:31:47 EST

> Is there anyway to sling OS commands around in Python like you can with the
> following constructs under Perl:
>
> open(FINGER,"finger dwwillia@cyclops|");
> print `finger dwwillia@cyclops`;
> ...
> I hope that it is as easy to do as it is in Perl.

At base, it's exactly as easy-- and exactly as clumsy --because Python &
Perl both pull off this trick using popen(3). But as usual, Perl adds
some ad hoc syntactic sugar, while Python supplies it via its uniform
object.method notation.

E.g., your first example would be (& read your popen manpage for
details; in general, the first argument is a sh command line, and the
second must 'r' or 'w'):

>>> import os
>>> finger = os.popen('finger tim', 'r')
>>>

and "finger" is now a Python open file object:

>>> finger
<open file 'finger tim', mode 'r' at 6d908>
>>> finger.__methods__
['close', 'fileno', 'flush', 'isatty', 'read', 'readline', 'readlines',
'seek', 'tell', 'write', 'writelines']
>>>

You can do whatever you want then. E.g.,

>>> finger.readline() # get next line
'Login name: tim \011\011\011In real life: Tim Peters\012'
>>> output = finger.readlines() # or read them all into a list
>>>

You second example would probably be better done via
os.system("finger dwwillia@cyclops")

but popen could be used for that too:

>>> for line in os.popen('finger tim','r').readlines():
... print line,
...
Login name: tim In real life: Tim Peters
Directory: /usr/local/users/tim Shell: /usr/local/bin/ksh
etc

If you grok popen and file.readlines, it's self-evident <wink>. You
might find the comma at the end of the "print" confusing: that's to
prevent Python from adding a redundant newline to each output line
("print" adds spaces & newlines to ease common usage;
sys.stdout.write(line)
is more like Perl's "print").

> I am not trying to cause a Perl/Python battle.

Ha! You're in one to the death now, pal <grin>.

exulting-in-the-fever-pitch-of-battle-ly y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp