Consider a python script error.py
import sys
sys.exit(3)
Invoking
python error.py; echo $?
yields the expected "3". However, consider runner.py
import os
result = os.system("python error.py")
print result
yields 768. It seems that somehow the result of python code has been leftshifted by 8, but how these two situations are different is not clear. What's going on?
This is occurring in python 2.5 and 2.6.
Python - Error Types. The most common reason of an error in a Python program is when a certain statement is not in accordance with the prescribed usage. Such an error is called a syntax error. The Python interpreter immediately reports it, usually along with the reason. Example: Error.
TypeErrors are raised mostly in situations where the programmer fails to check the type of object before performing an operation on them. They can be handled specifically by mentioning them in the except block.
To check your code, you must copy and paste, drag and drop a Python file or directly type in the Online Python editor below, and click on "Check Python syntax" button. You can see the user guide to help you to use this python checker tool.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
From the docs:
On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.
os.wait()
Wait for completion of a child process, and return a tuple containing its pid and exit status indication: 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); the high bit of the low byte is set if a core file was produced.
In your case, the return value 768 in binary is 00000011 00000000
. The high byte is 3.
os.system()
On Unix, the return value is the exit status of the process encoded in the format specified for wait()
os.wait()
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)
00000011 00000000
status signal
It should be safe to >> 8
the result to get your actual exit status (the result of system()
isn't very portable across platforms, however).
import os
result = os.system("python error.py")
print result >> 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With