call from pthon to shell

Andrew Robinson andrew3 at r3dsolutions.com
Mon Feb 11 20:00:38 EST 2013


On 02/12/2013 05:38 AM, Bqsj Sjbq wrote:
> >>> import os
> >>> os.system("i=3")
> 0
> >>> os.system("echo $i")
>
> 0
>
> why i can not get the value of i?
>
>
First:
os.system is only defined to give the return value (exit code) of the 
sub-process.

However, one way to get the output of shell commands is to use subprocess.

import subprocess
x = subprocess.check_output( [ "echo", "3,5,7" ] )

However, bash built-ins are not executables; nor is shell expansion 
performed; so you will actually need to do something like:
x=subprocess.check_output( [ "bash", "-c", "i=3; echo $i" ] )
 >>> x
 >>> '3\n'

To get the result you're interested in.
There may be better ways to get the result you want.... but hopefully 
you understand the problem better.

:)


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130212/82b8fd83/attachment.html>


More information about the Python-list mailing list