getting a string as the return value from a system command
tomf.sessile at gmail.com
Sun Apr 18 10:13:41 CEST 2010
On 2010-04-16 12:06:13 -0700, Catherine Moroney said:
> 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:
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().strip()
Looks ugly to me, but there we are.
More information about the Python-list