[Tutor] die or exit function?

Andy Koch andy.koch at pc-doctor.com
Wed Jun 14 16:26:17 CEST 2006


doug shawhan wrote:
> Hi Andy,
> 
> Putting a try:/except: loop in your __main__() (or whatever you call
> your base function) with sys.exit("Message") is pretty much the way I
> always do it.
> 
> try:
>     gak = puke + die
> except:
>     sys.exit("Oy!")
> 
> If you would like sys.exit() to provide you with a bit more
> information (like what actually happened during the failure and
> where!) I found this handy function:
> 
> 
> def formatExceptionInfo(maxTBlevel=5):
> 	cla, exc, trbk = sys.exc_info()
> 	excName = cla.__name__
> 	try:
> 		excArgs = exc.__dict__["args"]
> 	except KeyError:
> 		excArgs = "<no args>"
> 	
> 	excArgsString = ''
> 	for item in excArgs:
> 		excArgsString = excArgsString + ' ' + str(item)
> 	
> 	excTb = traceback.format_tb(trbk, maxTBlevel)
> 	excTbString = ''
> 	for item in excTb:
> 		excTbString = excTbString + " " + str(item)
> 	
> 	report = "%s %s %s"%(excName, excArgsString, excTbString)
> 	return(report)
> 
> This function now goes in most of what I do that requires error reporting.
> 
> Hope this helps!
> 
> On 6/13/06, Andy Koch <andy.koch at pc-doctor.com> wrote:
>> Bkgd: I've been doing PHP for the last several years.
>>
>> Q: In PHP there are functions die and exit which terminate processing of
>> a script with an optional string output.  Is there something similar to
>> this in Python?
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
Hi Doug,

copied and pasted, thanks

although my reason for the die() was that I've started using Python to 
do DB maintenance. I find it very handy (ie IDLE) and the DB api's for 
all the different DB's I work with are nice and standardized (PHP could 
learn a thing there).  One thing that has happened, though, is that I've 
clicked (via Winders Explorer) on a .py to open it for edit only to it 
have run, which is not what I want when the code could start modifying 
data.  Thus far it hasn't caused any damage.  So my safety check is to 
do a raw_input from a commonly included module which does the sys.exit() 
if running the code is not desired.

A basic safety catch.



More information about the Tutor mailing list