12

I want to pass two variables to the os.system() for example listing files in different format in specific directory like (ls -l testdirectory) in which both a switch and test directory are variable. I know for single variable this one works:

option=l os.sytem('ls -%s' option)

but I dont know how to pass two variables?

hamed
  • 1,325
  • 1
  • 15
  • 18
  • 3
    You shouldn't be using `os.system()` to begin with; use the much more flexible (and safer) `subprocess` module. (Your example won't work to begin with, either...) – Wooble Feb 28 '14 at 17:38
  • @Wooble meh technically your right ... i still use os.system regularly though also ... its just simple if thats all you need and you definately control the input ... – Joran Beasley Feb 28 '14 at 17:39
  • See http://stackoverflow.com/questions/12605498/how-to-use-subprocess-popen-python . – joel3000 Feb 28 '14 at 20:04
  • @Wooble I can't see any documentation [here](https://docs.python.org/2/library/subprocess.html#subprocess-replacements) that suggests security issues in using os.system. Can you elaborate? – codaamok Jul 20 '15 at 08:23
  • @codaamok See e.g. [Actual meaning of `shell=True` in `subprocess`](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) but it is also prominenetly mentioned in the `os.system` documentation, along with the recommendation to prefer the `subprocess` module. – tripleee Oct 12 '21 at 07:40

2 Answers2

24

you are asking about string formating (since os.system takes a string, not a list of arguments)

cmd = "ls -{0} -{1}".format(var1,var2)
#or cmd = "{0} -{1} -{2}".format("ls","l","a")
os.system(cmd)

or

cmd = "ls -%s -%s"%(var1,var2)

or

cmd = "ls -"+var1+" -"+var2
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
11

This, for example, works:

os.system('%s %s' % ('ls', '-l'))
Michael Lorton
  • 43,060
  • 26
  • 103
  • 144