从网络驱动器加载一些数据时,有时会发生权限错误,脚本会因权限错误而终止。
错误发生在这一行:
try:
data = self.data_file_loader(path)
except PermissionError:
print('here !!')
我假设该错误是由于网络驱动器中的某些问题而发生的。请注意,此错误只是偶尔发生或/和在大型数据集上迭代的情况下发生。
我使用的解决方法是捕获异常,等待 10 毫秒,然后重试,它有效,但除了花费更多时间加载数据之外,代码并不是很稳定。
try:
data = self.data_file_loader(path)
except PermissionError:
print('here !!')
time.sleep(10)
data = self.data_file_loader(path)
有更好的方法吗?
如果代码花费的时间太长,您可以使用安全网实现某种循环。它几乎基于您的建议,但具有更多“稳定性”。
MAX_TRIES = 5
SLEEP_TIME = 10
for _ in range(MAX_TRIES):
try:
data = self.data_file_loader(path)
break
except PermissionError:
time.sleep(SLEEP_TIME)
else:
# do something to exit the program here, this block is only called when data could not be read