Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

4
  • 1
    "The big advantage of os.system(...) was its simplicity. subprocess is better" - how subprocess is better? I am happily using os.system, not sure how switching to subprocess and remembering extra shell=True benefits me. What kind of thing is better in subprocess? Commented Mar 26, 2021 at 9:14
  • 1
    You're right in that os.system(...) is a reasonable choice for executing commands in terms of simple "blind" execution. However, the use cases are rather limited - as soon as you want to capture the output, you have to use a whole other library and then you start having both - subprocess and os for similar use cases in your code. I prefer to keep the code clean and use only one of them. Second, and I would have put that section at the top but the TL;DR has to answer the question exactly, you should not use shell=True, but instead what I've written in the Preferred Way section.
    – fameman
    Commented Mar 27, 2021 at 11:30
  • 2
    The problem with os.system(...) and shell=True is that you're spawning a new shell process, just to execute your command. This means, you have to do manual escaping which is not as simple as you might think - especially when targeting both POSIX and Windows. For user-supplied input, this is a no-go (just imagine the user entered something with " quotes - you'd have to escape them as well). Also, the shell process itself could load code you don't need - not only does it delay the program, but it could also lead to unexpected side effects, ending with a wrong return code.
    – fameman
    Commented Mar 27, 2021 at 11:34
  • 2
    Summing up, os.system(...) is valid to use, indeed. But as soon as you're writing more than a quick python helper script, I'd recommend you to go for subprocess.run without shell=True. For more information about the drawbacks of os.system, I'd like to propose you a read through this SO answer: stackoverflow.com/a/44731082/6685358
    – fameman
    Commented Mar 27, 2021 at 11:35