Re: [SLUG] Python questions

From: Paul M Foster (paulf@quillandmouse.com)
Date: Tue Aug 12 2003 - 00:14:20 EDT


On Tue, Aug 12, 2003 at 12:15:59AM +0000, Backward Thinker wrote:

>
> 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()

That would be the correct answer. I searched the internet a little after
I wrote this email, and found the sys.exit() function in some sample
code on the internet.

> (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.

<snip>

The exception thing explains why python acts so oddly (to me). The
single open_file() function is probably the best idea in the long run.

It's funny, I'm converting some perl code over to python. I normally
code in C, and for some reason, perl was vastly easier to learn than
python is. Weird.

Anyway thanks,

Paul

-----------------------------------------------------------------------
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:30:03 EDT