Python string formatting
I'm building up several command strings to pass to os.system. I want to group the common stuff into a string then add the specific stuff as needed. For example:
CMD = "python app.py %s -o %s > /dev/null"
option1 = "-i 192.169.0.1"
option2 开发者_如何学Python= "results-file"
cmd = CMD, (option1, option2) #doesn't work
os.system(cmd)
I know cmd is a tuple. How do I get cmd to be the command string I want?
You use the %
operator.
cmd = CMD % (option1, option2)
See also: Python documentation on string formatting
You could do it this way using the string format()
method which processes Format String Syntax:
CMD = "python app.py {} -o {} > /dev/null"
option1 = "-i 192.169.0.1"
option2 = "results-file"
os.system(CMD.format(option1, option2))
cmd = CMD % (option1, option2)
This is explained here.
精彩评论