Python is driving me crazy; I always have difficulty using variables in PATH. My version is Python 2.4.3
>>> import os
>>> a = "httpd"
>>> cmd = '/etc/init.d/+a restart'
>>> print cmd
/etc/init.d/+a restart
>>>
How do I put a /etc/init.d/httpd in cmd variable so I can use os.system(cmd)?
2 Answers 2
For python v> 2.7
cmd = '/etc/init.d/{} restart'.format(a)
or
cmd = '/etc/init.d/'+a+' restart'
But you should probably look into using subprocess.
4 Comments
.format for newer versions of python, thanks to your answer.'{0}' rather than '{}'you need something like:
cmd = '/etc/init.d/%s restart' % a
If you need to do multiple substitutions, you could do something like:
cmd = '/etc/init.d/%s %s' % ( 'httpd', 'restart' )
In this form, '%s' is a place holder. Each '%s' gets replaced by an item in the corresponding tuple on the right hand side of the % operator (which is the string interpolation operator I suppose). More details can be found in the String Formatting section of the reference
Starting with python2.6, there's a new way to format strings using the .format method, but I guess that doesn't help you very much.