即使存在异常,我仍试图继续执行我的代码。只需打印异常并继续执行代码即可。
下面是示例:
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
请帮助
答案 0 :(得分:0)
需要导入errno模块。
errno模块定义了许多符号错误代码
答案 1 :(得分:0)
您忘记了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")
答案 2 :(得分:0)
只需:
except OSError:
pass
或except Exception
排除所有例外(尽管不理想)。您正在尝试使用不导入的模块(我认为您不需要为此脚本导入errno)。