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 = "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?
asked Jan 26, 2011 at 11:11
VacuumTube
4,1614 gold badges24 silver badges19 bronze badges
3 Answers 3
You use the % operator.
cmd = CMD % (option1, option2)
answered Jan 26, 2011 at 11:14
Sebastian Paaske Tørholm
51.3k11 gold badges103 silver badges123 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
S.Lott
You should use the format function.
cmd= "python app.py {0:s} -o {1:s} > /dev/null".format( option1, option2 )Ben Hoyt
@S.Lott Yes,
.format() is definitely nicer. However, you don't need the ":s" in the format string -- "s" is the default type. So just "{0} -o {1}" is fine. But @Joe is right, subprocess is the way to go here!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))
answered Jan 26, 2011 at 11:36
martineau
124k29 gold badges181 silver badges319 bronze badges
Comments
cmd = CMD % (option1, option2)
This is explained here.
answered Jan 26, 2011 at 11:14
kynnysmatto
3,94027 silver badges29 bronze badges
2 Comments
kynnysmatto
yeah, but it only concatenated those strings, but you wanted to replace %s's by those option strings
VacuumTube
Yes, appreciate that. I will give the prize to Sebastian P :-), but thanks anyway.
lang-py
subprocess.callwith a list of arguments. docs.python.org/library/subprocess.html