getting a string as the return value from a system command
CHEN Guang
dr.cg at 126.com
Sat Apr 17 02:49:56 EDT 2010
> Catherine Moroney wrote:
>> 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.
>>
>> Thanks for any tips,
>>
>> 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 -=-
>
os.popen3() gives not only result but also error prompt (in case an error or warning happens)
stdin,stdout,stderr = os.popen3('uname -srvi')
resultText = stdout.read()
errorText = stderr.read()
For more examples of os.popen3() please look at source code of PythoidC (http://pythoidc.googlecode.com or http://pythoidc.sf.net )
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100417/7d76442b/attachment-0001.html>
More information about the Python-list
mailing list