What's the best way to wrap a whole script in try..except?

Hari Sekhon sekhon.hari at googlemail.com
Thu Jun 22 07:33:17 EDT 2006


On 21/06/06, Bruno Desthuilliers <onurb at xiludom.gro> wrote:
>
> Hari Sekhon wrote:
> > I want to wrap a whole script in try ... except. What is the best way of
> > doing this?
> >
> > Consider the following: -
> >
> > try:
> >    import <modules>
> >
> >    <CODE>
> >
> >    def notifyme(traceback):
> >       code to tell me there is a problem
> >
> > except Exception, traceback:
> >    notifyme(traceback)
> >
> >
> > Would this code not work because if any part of <CODE> encounters an
> > exception then it won't reach the notifyme() function definition and
> > therefore the whole thing won't work and I won't get notified when a
> > traceback occurs, in fact the call to notifyme() under except will
> > itself probably trace back as well!
>
> Yes.
>
> > Do I have to instead do:
> >
> > import <a couple of modules>
> > def notifyme():
> >    code to tell me there is a problem
> >
> > try:
> >    <CODE>
> >
> > except Exception, traceback:
> >    notifyme(traceback)
> >
>
> Would work, but...
>
> > How you you handle this?
>
> I don't put the main logic at the top level - I use a main() function.
>
> import <some modules>
> def notifyme(e):
>   # code here...
>
> def main(*args):
>   try:
>     # code here
>     return 0
>
>   except Exception, e:
>     notifyme(e)
>     return <some-non-zero-error-code>
>
> if __name__ == '__main__':
>   import sys
>   sys.exit(main(*sys.argv))
>
> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in 'onurb at xiludom.gro'.split('@')])"
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Why bother passing the args in def main(*args): and main(*sys.argv)?
Couldn't you just use sys.argv straight off inside main, no passing args
around....

I can see you are probably a C programmer as well?

-h
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20060622/01086e7c/attachment.html>


More information about the Python-list mailing list