Re: [SLUG] Python questions

From: Backward Thinker (backwardthinker@juno.com)
Date: Mon Aug 11 2003 - 20:15:59 EDT


I don't have a python interpreter handy, so take this with a grain of salt.

> In C and the like, you can simply execute a return or exit anywhere
> in main(), but not in python.

Return should work from anywhere in a function definition. If you're not in a function, then you are probably looking for sys.exit().

import sys
sys.exit(42)
or more likely,
sys.exit()
(0 is probably the default)

> The second problem is sometimes related to the first. Apparently,
> when you open a file, as in:
>
> open(filename, 'r')
>
> if the file doesn't exist, you get this hairy error message and the
> interpreter just dumps out. I've never seen this kind of behavior
> before. I'd expect something more like
>
> if open(filename, 'r'):
> do_stuff
> else:
> couldnt_open_the_file_stuff
>
> But that doesn't work. The only way I can see around this is to
> surround every call to open() with a try/except block. That's clunky
> to me.
> Anyone know something I don't?

Yup, that's kinda how python is. Errors typically generate exceptions, and python catches the exception. Depending on how many opens you have and how much you hate try except blocks, you can write your own open function once with one try except block, which returns None if it catches an exception. So instead of writing 50 try except blocks, you can just write the one function, and call your new function with the filename as an arg, and test if your function call returned a file object or None... no more try except blocks necessary. Also, I don't remember how the file() function handled this. It was depreciated in favor of open, though. I think it may have been the same, or it may have actually created the file? I don't remember. You could also get into the os. file functions, but my guess is in you're case you're best off biting the bullet and having however many try except statements you need, or the one function.

~ Daniel

________________________________________________________________
The best thing to hit the internet in years - Juno SpeedBand!
Surf the web up to FIVE TIMES FASTER!
Only $14.95/ month - visit www.juno.com to sign up today!
-----------------------------------------------------------------------
This list is provided as an unmoderated internet service by Networked
Knowledge Systems (NKS). Views and opinions expressed in messages
posted are those of the author and do not necessarily reflect the
official policy or position of NKS or any of its employees.



This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 16:28:26 EDT