Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: global name 'PermissionError' is not defined (python 2.x)

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?

like image 546
ofer.sheffer Avatar asked Aug 13 '13 01:08

ofer.sheffer


2 Answers

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.

like image 194
paxdiablo Avatar answered Oct 10 '22 19:10

paxdiablo


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.

like image 35
ofer.sheffer Avatar answered Oct 10 '22 20:10

ofer.sheffer