简体   繁体   中英

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) ?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM