On 2010-04-18 03:13 , TomF wrote:
On 2010-04-16 12:06:13 -0700, Catherine Moroney said:
Hello,
I want to call a system command (such as uname) that returns a string,
and then store that output in a string variable in my python program.
What is the recommended/most-concise way of doing this?
I could always create a temporary file, call the "subprocess.Popen"
module with the temporary file as the stdout argument, and then
re-open that temporary file and read in its contents. This seems
to be awfully long way of doing this, and I was wondering about
alternate ways of accomplishing this task.
In pseudocode, I would like to be able to do something like:
hostinfo = subprocess.Popen("uname -srvi") and have hostinfo
be a string containing the result of issuing the uname command.
Here is the way I do it:
import os
hostinfo = os.popen("uname -srvi").readline().strip()
(I add a strip() call to get rid of the trailing newline.)
os.popen has been replaced by the subprocess module, so I suppose the
new preferred method is:
from subprocess import Popen, PIPE
hostinfo = Popen(["uname", "-srvi"], stdout=PIPE).communicate()[0].strip()
Looks ugly to me, but there we are.
The easy way to fix things that look ugly but are the right thing to do is to
wrap them up into a utility function and call the utility function everywhere.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
--
http://mail.python.org/mailman/listinfo/python-list