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.
Thanks for any tips,
Catherine
p = subprocess.Popen(['uname', '-srvi'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
--
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
Thanks, I knew there had to be a more elegant way of doing that.
Catherine
import os
txt = os.popen("uname -srvi")
hostinfo = txt.readline()
Or if the command outputs a number of lines (such as 'ls'),
use txt.readlines() to put the result into a list of strings.
-=- Larry -=-
The subprocess module is the preferred choice over either of those functions.
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.
-Tom
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.