...

View Full Version : Process different commands based on error



pippin418
05-07-2010, 10:35 PM
Okay, I have this:


if com == 'del':
rem = raw_input("What file: ")
rea = raw_input("Really remove %s? (y/n)" % rem)
if rea in ('y'):
try:
os.remove(rem)
except OSError:
print "That is a directory, del deletes files. Use ddel instead."
raw_input("Press ENTER to return.")
goto .home
else:
goto .home
elif rea in ('n'):
goto .home

Now, don't worry about the goto, I have a module installed for it, and I know you're not supposed to use it... I'm using it on my computer though. Anyway.

In that script you should see the except OSError:, that works great, but there's more than one type of error you can get with it. How can I run different commands based on the different errors? (All of them will be OSErrors)\

Thanks

Samhain13
05-08-2010, 09:04 PM
More stuff here: http://docs.python.org/tutorial/errors.html

For your problem:

some_file_name = "whatever"

try:
os.remove(some_file_name)

except OSError as (errno, strerror):
# Decide what to do based on error code:
# File doesn't exist.
if errno == 2:
print "Do something..."
# Trying to delete a directory.
elif errno == 21:
print "Do something else..."
# elif errno = ??: do something else....

else:
print "LOLWUT?"

:D

pippin418
05-09-2010, 07:49 AM
Thanks a lot.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum