32

The Python manual says nothing about whether os.system("cmd") waits or not for a process to end:

To quote the manual:

Execute the command (a string) in a subshell.

It looks like it does wait (same behaviour as Perl's system). Is this correct?

Eric
  • 95,302
  • 53
  • 242
  • 374
Adobe
  • 12,967
  • 10
  • 85
  • 126
  • Successfully waits when tested with Ubuntu 20.04 Python 3.8.5 ```import os os.system('echo $(pwd); sleep 5')``` – MiKK Apr 09 '22 at 16:26

3 Answers3

36

Yes it does. The return value of the call is the exit code of the subprocess.

Russel Winder
  • 3,436
  • 1
  • 17
  • 12
  • Is this still true for py3.x? http://stackoverflow.com/questions/14059558/why-is-python-no-longer-waiting-for-os-system-to-finish – alvas Aug 03 '15 at 11:38
  • 2
    Yes, but people should not be using os.system at all. Use the subprocess package, probably one of the helper functions: call, check_call, check_output. – Russel Winder Aug 04 '15 at 11:25
  • 2
    In python 3.5 call, check_call, and check_output have been replaced with the run function. – Russel Winder Sep 07 '16 at 10:50
  • 5
    @RusselWinder: Why don't you add this to your answer? - explaining how one shoud use the subprocess package instead! – strpeter Jan 11 '18 at 16:24
14

The manual doesn't explicitly say, but it does imply that it waits for the end of the process by saying that the return value is the return value of the program.

So to answer your question, yes it does wait.

obmarg
  • 9,369
  • 36
  • 59
2

On Mac it waits, but on Linux it does not (Debian, python 3.7.3).

Fixed using subprocess:

import subprocess

subprocess.run("cmd")
Max Farsikov
  • 2,451
  • 19
  • 25
  • Strange how, as a replacement, ```subprocess.run(['echo', '$(pwd)'])``` gives different output to ```os.system('echo $(pwd)')``` – MiKK Apr 09 '22 at 16:19