0

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?

4
  • 5
    Just in case this is a real example, you should avoid concatenating strings to create shell commands for safety reasons. Use subprocess.call with a list of arguments. docs.python.org/library/subprocess.html Commented Jan 26, 2011 at 11:18
  • @Joe. Good point. I am only using this in my unit tests of app.py so I guess it's okay for this. Commented Jan 26, 2011 at 11:23
  • @Joe Is that not only a problem if the strings are coming from outside. If they are hardcoded like this what can go wrong? Commented Jan 26, 2011 at 11:38
  • Well, for starters, you might decide to take the string from outside in the future. Or you could make a mistake with the argument. It's just safest and best-practice. It's also a bit easier to read and saves you having to format strings. Commented Jan 26, 2011 at 13:51

3 Answers 3

3

You use the % operator.

cmd = CMD % (option1, option2)

See also: Python documentation on string formatting

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

2 Comments

You should use the format function. cmd= "python app.py {0:s} -o {1:s} > /dev/null".format( option1, option2 )
@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!
3

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

Comments

0
cmd = CMD % (option1, option2)

This is explained here.

2 Comments

yeah, but it only concatenated those strings, but you wanted to replace %s's by those option strings
Yes, appreciate that. I will give the prize to Sebastian P :-), but thanks anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.