Satish
Satish

Reputation: 17487

python variable in command to execute with os.system

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

Answers (2)

mgilson
mgilson

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

askewchan
askewchan

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

Related Questions