首页 > 解决方案 > Python 在异常情况下继续执行

问题描述

尽管存在异常,我仍在尝试继续使用我的代码。只需打印异常并继续代码。

以下是示例:

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")

但它从不打印完成。

控制台输出

./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

请提供任何帮助

标签: pythonpython-3.xpython-2.7exception

解决方案


需要导入 errno 模块。

errno 模块定义了许多符号错误代码


推荐阅读