Simple way of handling errors
Peter Otten
__peter__ at web.de
Thu May 7 04:01:57 EDT 2009
TomF wrote:
> As a relative newcomer to Python, I like it a lot but I'm dismayed at
> the difficulty of handling simple errors. In Perl if you want to
> anticipate a file-not-found error you can simply do:
>
> open($file) or die("open($file): $!");
>
> and you get an intelligible error message. In Python, to get the same
> thing it appears you need at least:
>
> try:
> f=open(file)
> except IOError, err:
> print "open(%s): got %s" % (file, err.strerror)
> exit(-1)
>
> Is there a simpler interface or idiom for handling such errors? I
> appreciate that Python's exception handling is much more sophisticated
> but often I don't need it.
>
> -Tom
While you are making the transition you could write
from perl_idioms import open_or_die
f = open_or_die("does-not-exist")
with the perl_idioms module looking like
import sys
def open_or_die(*args):
try:
return open(*args)
except IOError, e:
sys.exit(e)
Peter
More information about the Python-list
mailing list