1

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

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Careful, your second version is missing a space
@mgilson Thanks, fixed. Also noted that .format for newer versions of python, thanks to your answer.
Actually, the way you have it is only python2.7 and newer. with python2.6 you'd need '{0}' rather than '{}'
epic win... You are my hero :)
2

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.

2 Comments

Could you explain those %s and % doing there?
@Satish -- Added some explanation and a link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.