Read stdout from shell command, was: Becoming root

Michael P. Reilly arcege at shore.net
Sun Sep 26 08:34:39 EDT 1999


Donn Cave <donn at u.washington.edu> wrote:
: Quoth wware-nospam at world.std.com (Will Ware):
: ...
: | The thing I'd really like to know is how to do the Python
: | equivalent of a shell command of this form:
: |
: | variable = `some shell command`
: |
: | where "some shell command" prints to standard output.
: | I find I do this quite frequently, usually using something like
: | os.popen('some shell command').readline()[:-1] and sure, it works,
: | but it's really ugly, and I'm always left with the nagging suspicion
: | that since I didn't explicitly close the os.popen(), it might still
: | be floating around.

: Empirically, the pipe file descriptor does close when the object goes
: out of scope, from what I see with other file descriptor unit numbers
: allocated subsequently by pipe() or open().

: I rolled my own pipe/fork/exec system a ways back and use it a lot,
: and you're welcome to it -
: ftp://ftp.u.washington.edu/pub/user-supported/donn/cmdproc.py

: I use it mostly the way you describe, to store the output of a
: command in a variable.  The long way to spell it is

:  variable = cmdproc.RaiseCommand('/bin/sh',
:                 ('sh', '-c', 'some shell command')).expand()

: (Actually I often invoke the command directly rather than through the
: shell, but the above example serves to illustrate both.)

: The RaiseCommand class also raises an exception when the command exits
: with an error, with the exception value set to the diagnostic (unit 2)
: output.  I think that's the feature that really sets this apart from
: just another way to spell popen().

There is also the standard library module "commands", which does all
but remove the trailing newline (if present).  It uses os.popen (and
implicit Bourne syntax), but does quote the arguments for you.

(Although, Donn's would probably be more efficient. :)

  -Arcege





More information about the Python-list mailing list