Having problems with Exceptions
Thomas Wouters
thomas at xs4all.net
Thu Jul 6 16:30:42 EDT 2000
On Thu, Jul 06, 2000 at 10:03:44AM -0600, m wrote:
> I'm new at Python coding and am trying to catch
> errors returned by os.open with exception handling.
> All errors with os.open are returned with an OSError
> exception. So, how do I split out the individual errors
> with something as simple as:
> try:
> file=os.open("test",os.O_RDWR | os.O_CREAT | os.O_EXCL, 0444)
>
> except OSError:
> {want to do different things here for errno EEXIST (file exists)
> or EACCES (Permission denied), etc.}
> I have looked at the tuple returned by sys.exc_info() and can
> extract the *text* of the Python error message
> (i.e. "[Errno 17] File exists"), but not the numeric error number.
> I certianly don't want to have to rely on parsing the text to get
> the actual error. I'm sure there is an easy answer to this if
> someone would be kind enough to help me.
You're looking for the 'errno' attribute of OSError objects. You should
compare them to constants defined in errno, for compatibility, like so:
import os, errno
try:
file = os.open("test", ... )
except OSError, e:
if e.errno == errno.EEXIST:
print "The file eixsts already"
elif e.errno == errno.EACCES:
print "Can't touch this"
elif e.errno == ELOOP:
print "symlink after " * 1024 + "symlink!"
<etc>
--
Thomas Wouters <thomas at xs4all.net>
Hi! I'm a .signature virus! copy me into your .signature file to help me spread!
More information about the Python-list
mailing list