What is the return value of os.system() in Python?

user813713 picture user813713 · Jun 24, 2011 · Viewed 154k times · Source

I came across this:

>>> import os
>>> os.system('ls')
file.txt README
0

What is return value of os.system()? Why I get 0?

Answer

rubik picture rubik · Jun 24, 2011

The return value of os.system is OS-dependant.

On Unix, the return value is a 16-bit number that contains two different pieces of information. From the documentation:

a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero)

So if the signal number (low byte) is 0, it would, in theory, be safe to shift the result by 8 bits (result >> 8) to get the error code. The function os.WEXITSTATUS does exactly this. If the error code is 0, that usually means that the process exited without errors.

On Windows, the documentation specifies that the return value of os.system is shell-dependant. If the shell is cmd.exe (the default one), the value is the return code of the process. Again, 0 would mean that there weren't errors.

For others error codes: