Passing Variables to the System Command

 


Tzu-Ming Chern wrote:


> Hi Python tutors,

>

> I'm having problems finding a way to pass variables when using the systems
> command in python. For example, in a simple python script, I would like to
> run another python script using the systems command. This python script
> takes the variables (argument1 and 2) as commandline arguments, which are
> filenames infact. The python scripts and all the filenames are in the same
> directory. See the following for example:
>
> import os
>
> argument1 = filename1
> argument2 = filename2
>
> os.system("some_other_python_script.py argument1 argument2") What you need to do is construct a string using the values of those variables. The best way to do this is usually string formatting with the % operator.

cmdstring = "some_other_script.py %s %s" % (argument1 argument2) os.system(cmdstring)

You can do this all on one line, too, but I separated it specifically to show that this is a feature of strings rather than something related to os.system() or the os module.

See http://docs.python.org/lib/typesseq-strings.html for a more detailed look at how to use string formatting.

References:

https://mail.python.org/pipermail/tutor/2004-August/030909.html