简体   繁体   中英

Python Continue with execution in case of exception

I am trying to continue with my code eventhough exception is present. Just print the exception and continue with code.

Below is sample:

def mkdir(path):
        mypath = "./customers/"+path
        print(mypath)
        try:
            os.makedirs(mypath)
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(mypath):
                pass

if __name__ == '__main__':
    item = 'dev'
    mkdir(item)
    print("Done")

But It never prints Done.

Console OutPut

./customers/dev
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-45-3ce58775d916> in mkdir(path)
      4         try:
----> 5             os.makedirs(mypath)
      6         except OSError as exc:

/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py in makedirs(name, mode, exist_ok)
    220     try:
--> 221         mkdir(name, mode)
    222     except OSError:

FileExistsError: [Errno 17] File exists: './customers/dev'

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-45-3ce58775d916> in <module>
     10 if __name__ == '__main__':
     11     item = 'dev'
---> 12     mkdir(item)
     13     print("Done")

<ipython-input-45-3ce58775d916> in mkdir(path)
      5             os.makedirs(mypath)
      6         except OSError as exc:
----> 7             if exc.errno == errno.EEXIST and os.path.isdir(mypath):
      8                 pass
      9 

NameError: name 'errno' is not defined

Any help please

Need to import errno module.

The errno module defines a number of symbolic error codes

You forgot to import errorno

import os
import errno


def mkdir(path):
    mypath = "./customers/" + path
    print(mypath)
    try:
        os.makedirs(mypath)
    except OSError as exc:
        print(exc.errno)
        if exc.errno == errno.EEXIST and os.path.isdir(mypath):
            pass


if __name__ == '__main__':
    item = 'dev'
    mkdir(item)
    print("Done")

Just do:

except OSError:
    pass

or except Exception to except all exceptions (albeit not ideal). You are trying to use a module without importing (and I don't think you need to import errno for this script).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM