VacuumTube
VacuumTube

Reputation: 4101

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 = "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?

Upvotes: 0

Views: 666

Answers (3)

martineau
martineau

Reputation: 123393

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

Upvotes: 3

You use the % operator.

cmd = CMD % (option1, option2)

See also: Python documentation on string formatting

Upvotes: 3

kynnysmatto
kynnysmatto

Reputation: 3892

cmd = CMD % (option1, option2)

This is explained here.

Upvotes: 0

Related Questions