atexit, sys.exit, sys.exitfunc, reaching end of source code

Wojciech Muła wojciech_mula at
Thu Jul 12 01:32:22 CEST 2007

carl.dhalluin at wrote:
> I am playing with the atexit module but I don't find a way to see the
> difference
> between a script calling sys.exit(<returncode>) and the interpreting
> arriving at the end
> of the source code file. This has a semantic difference for my
> applications.
> Is there a way to determine in an exithandler (that is registered
> using atexit.register)
> how I exited?

Actually sys.exit raises exception SystemExit, but if interpreter
reaches end of script exception is not raised.  Try something
like this:

if __name__ == '__main__':
	exit_code_for_exithandler = None
	except SystemExit, e:
		exit_code_for_exithandler = e.code
		print "sys.exit called"
		print "end of script"


More information about the Python-list mailing list