>>> pipe.read()
'Bye sys world\012'
>>> stat = pipe.close() # returns exit code
>>> stat
10752
>>> hex(stat)
'0x2a00'
>>> stat >> 8 # extract status from bitmask on Unix-likes
42
>>> pipe = os.popen('python testexit_os.py')
>>> stat = pipe.close()
>>> stat, stat >> 8
(25344, 99)
This code works the same under Cygwin Python on Windows. When using os.popen
on such Unix-like platforms, for reasons we won’t go into here, the exit status is actually
packed into specific bit positions of the return value; it’s really there, but we need to
shift the result right by eight bits to see it. Commands run with os.system send their
statuses back directly through the Python library call:
>>> stat = os.system('python testexit_sys.py')
Bye sys world
>>> stat, stat >> 8
(10752, 42)
>>> stat = os.system('python testexit_os.py')
Bye os world
>>> stat, stat >> 8
(25344, 99)
All of this code works under the standard version of Python for Windows, too, though
exit status is not encoded in a bit mask (test sys.platform if your code must handle
both formats):
C:\...\PP4E\System\Exits> python
>>> os.system('python testexit_sys.py')
Bye sys world
42
>>> os.system('python testexit_os.py')
Bye os world
99
>>> pipe = os.popen('python testexit_sys.py')
>>> pipe.read()
'Bye sys world\n'
>>> pipe.close()
42
>>>
>>> os.popen('python testexit_os.py').close()
99
Program Exits | 217