Read stdout from shell command, was: Becoming root
Charles G Waldman
cgw at fnal.gov
Fri Sep 24 13:22:48 EDT 1999
Will Ware writes:
> 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,
Well, I agree that using popen is kind of ugly; generally if there's
a way to get at the info by using some Python code rather than relying
on an external program, that's always better, e.g. like using
os.listdir instead of popen'ing the "ls" command, to take a silly
example.
But when you absolutely must use some shell command, then popen is the
way to go.
> 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.
pipe = os.popen("the_command",'r')
output = pipe.readlines()
exit_status = pipe.close()
This has the double advantage of not only explicitly closing the pipe
object, but also collecting the exit status of the invoked command.
If you want to be really proper, you'll use some try/except around
this, in case the program isn't found, an IO error occurs, etc.
HTH,
cgw
More information about the Python-list
mailing list