Reputation: 17487
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)
?
Upvotes: 1
Views: 10071
Reputation: 310257
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.
Upvotes: 2
Reputation: 46578
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
.
Upvotes: 3