I need a method to run a python script file, and if the script fails with an unhandled exception python should exit with a non-zero exit code. My first try was something like this:
import sys
if __name__ == '__main__':
try:
import <unknown script>
except:
sys.exit(-1)
But it breaks a lot of scripts, due to the __main__
guard often used. Any suggestions for how to do this properly?
if you want to run a script within a script then import isn't the way; you could use exec if you only care about catching exceptions:
you can also compile the code first with
if you are planning to execute the script more than once and exec the result in the namespace
or use subprocess as described above, if you need to grab the output generated by your script.
Python already does what you're asking:
After some edits from the OP, perhaps you want:
Correct me if I am confused here.