python - 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
请提供任何帮助
解决方案
需要导入 errno 模块。
errno 模块定义了许多符号错误代码
推荐阅读
- mysql - 用于划分子集的 mySQL 查询
- javascript - 如何在jquery on()中获取选择器类元素的ID
- javascript - 网站性能对少数用户来说很慢,对其他用户来说非常快
- bash - 拆分字符串变量并仅使用节 bash
- python - 如何将svg转换为ipe?
- android - 您可以使用 WorkManager 在方法上运行单元吗?
- troff - 尾随空格在 Troff 手动文件中是否重要?
- sql - 在包含外汇交易数据的 SQL 表中获取第一个月的利润
- vcf-variant-call-format - VCF 文件的 ALT 列包含替代核苷酸 AND <*>
- excel - 我需要在三列中添加时间然后在第 4 列中添加总时间的 Excel 情况