11

According to this:

In the previous section, we saw that os.system() function works fine. But it’s not recommended way to execute shell commands. We will use Python subprocess module to execute system commands.

The writer never mentions why os.system() is not the recommended way in his/her post. May I know why it's not recommended?

Is there any security bug in os.system() that makes it not recommended way to execute shell commands?

1 Answers1

9

os.system only takes a single string, containing a shell command, as an argument. This requires the user to be aware of how the shell will process the string before the desired command can be run.

From its own documentation:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    Thanks @chepner. So this has nothing to do with security? **Post update** Is there any security bug in `os.system()` that makes it not recommended way to execute shell commands? –  Jul 31 '19 at 14:51
  • 1
    Security comes into it, as you might be tempted to construct a command string like `os.system("someCommand " + argument)`. This opens you to the possibility of code injection, since `argument` is *not* the single argument to `someCommand`; it's arbitrary code which, when combined with `someCommand`, forms a command line which a shell has to parse. `subprocess.Popen(["someCommand", argument])` does what you expect and intend: it runs `someCommand` with a single argument. – chepner Jul 31 '19 at 14:55