0

Is there a functional difference between the following two methods?

os.system("echo $HOME")
subprocess.call("echo $HOME")

This is a similar question to this one, but that question really focuses more on subprocess.Popen().

alex
  • 6,818
  • 9
  • 52
  • 103
  • 2
    Yes. And you should basically always use `subprocess`. If you want a more complete answer, you need to first read the docs, and then tell us what parts you don't understand. – abarnert Mar 09 '18 at 01:38
  • Side-note: Both of them are completely pointless, since they're basically equivalent to `print(os.environ["HOME"])`. – ShadowRanger Mar 09 '18 at 01:40
  • Also see https://docs.python.org/3/library/subprocess.html#replacing-os-system (in this case, of course, "Calling the program through the shell is usually not required" does not apply…) – abarnert Mar 09 '18 at 01:41
  • If you're going to ask a question similar to others, please be more explicit/specific in the question about *exactly* what aspect of your problem isn't addressed elsewhere ("From question X, I understand A, but this still doesn't answer B"). – Charles Duffy Mar 09 '18 at 02:36
  • @ShadowRanger It's just sample code. Side-note: I guess using `subprocess` is pointless by the same logic, because you could just type whatever you need on the shell. – alex Mar 09 '18 at 03:05
  • @abarnert Please don't assume I didn't read the docs. The [documentation on os.system](https://docs.python.org/2/library/os.html#os.system) is clear as mud unless you are intimately familiar with native C - we cannot all be so fortunate. – alex Mar 09 '18 at 03:16

1 Answers1

1

If you're running python (cpython) on windows the <built-in function system> os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.

While subprocess.call will use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.

The above points should answer your questions about the main differences (structurally)... That said, I'd suggest you follow the most important advice from the os.system docs, which is:

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.

BPL
  • 9,632
  • 9
  • 59
  • 117