LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   python, os.system() function. howto use python variables? (http://www.linuxquestions.org/questions/programming-9/python-os-system-function-howto-use-python-variables-572485/)

jhwilliams 07-26-2007 01:56 PM

python, os.system() function. howto use python variables?
 
i would like to do something like this in python:

Code:

myCoolVariable="some_string"
os.system("echo myCoolVariable")

however, the system function views myCoolVariable as a string literal, not as a python variable. What do I do to get around this?

Thank you,
Jameson

pixellany 07-26-2007 02:35 PM

It needs to be one of these forms:
Code:

>>> os.system('echo "asdg"')
asdg
0
>>> os.system("echo 'asdgwere'")
asdgwere
0

The outer quotes define the string to be passed to the shell, and the inner quotes define what gets passed to echo.

jhwilliams 07-26-2007 02:56 PM

That is just printing out the string literals you are passing to echo - i am looking to resolve the python varaible myCoolVariable before the execution of echo in the sysem() call.

For example, I would like:

Code:

$ python
>>>hamburger="potato"
>>>import os
>>>os.system("echo 'hamburger'")

to somehow produce

Code:

potato
0

in this case i could just write "potato" directly, but things get stickier when i want to say

Code:

hamburger=os.system('echo $MY_SHELL_VAR | sed "s/longsed/replacement/g"')
, or something of that flavour

pixellany 07-26-2007 05:14 PM

Bingo!!!

Code:

>>> string="python is cool"
>>> cmd="echo "+string
>>> os.system(cmd)
python is cool
0
>>>


jhwilliams 07-26-2007 06:18 PM

Thanks pixellany!

paddy3118 07-28-2007 02:56 AM

Or do string interpolation:

Code:

bash$ python
Python 2.4.3 (#1, May 18 2006, 07:40:45)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from os import system
>>> food = 'spam'
>>> system('echo %(food)s' % locals())
spam
0
>>>

- Paddy.


All times are GMT -5. The time now is 04:31 PM.