Question

The following line:

except (IOError, PermissionError, FileNotFoundError) as e:

Gives the following error message when I run it with python 2.75:

NameError: global name 'PermissionError' is not defined

But everything runs fine with python 3.3.

Thoughts/suggestions?

Was it helpful?

Solution 2

This solved the issue for me for python 2.75 and 3.31:

from errno import EACCES, EPERM, ENOENT

def print_error_message(e, file_name):
    #PermissionError
    if e.errno==EPERM or e.errno==EACCES:
        print("PermissionError error({0}): {1} for:\n{2}".format(e.errno, e.strerror, file_name))
    #FileNotFoundError
    elif e.errno==ENOENT:
        print("FileNotFoundError error({0}): {1} as:\n{2}".format(e.errno, e.strerror, file_name))
    elif IOError:
        print("I/O error({0}): {1} as:\n{2}".format(e.errno, e.strerror, file_name))
    elif OSError:
        print("OS error({0}): {1} as:\n{2}".format(e.errno, e.strerror, file_name))

try:
...
except (IOError, OSError) as e:
    print_error_message(e,full_name)
    sys.exit()
except:
    print('Unexpected error:', sys.exc_info()[0])
    sys.exit()

Thoughts/comments/suggestions are welcome.

OTHER TIPS

There was no PermissionError in Python 2.7, it was introduced in the Python 3.3 stream with PEP 3151. For a list of the 2.7 exceptions, see here.

PEP 3151 was an attempt to clean up the exception hierarchy for OS and I/O related exceptions.

I believe, before then, the equivalent would have been to catch OSError and check errno for EPERM, or IOError and check errno for EACCES.

You could always check if you're running under Python 3.3 or greater and, if not, create your own PermissionError. That'll never be thrown of course so you'll need to catch the two possibilities shown above as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top