python – 避免程序退出I / O错误
发布时间:2020-12-20 12:25:08 所属栏目:Python 来源:网络整理
导读:我有一个广泛使用shutil.copy2的 Python脚本.由于我使用它来通过网络复制文件,因此I / O错误过于频繁,从而导致程序执行中止: Traceback (most recent call last): File "run_model.py",line 46,in module main() File "run_model.py",line 41,in main trace
我有一个广泛使用shutil.copy2的
Python脚本.由于我使用它来通过网络复制文件,因此I / O错误过于频繁,从而导致程序执行中止:
Traceback (most recent call last): File "run_model.py",line 46,in <module> main() File "run_model.py",line 41,in main tracerconfigfile=OPT.tracerconfig) File "ModelRun.py",line 517,in run self.copy_data() File "ModelRun.py",line 604,in copy_ecmwf_data shutil.copy2(remotefilename,localfilename) File "/usr/lib64/python2.6/shutil.py",line 99,in copy2 copyfile(src,dst) File "/usr/lib64/python2.6/shutil.py",line 54,in copyfile copyfileobj(fsrc,fdst) File "/usr/lib64/python2.6/shutil.py",line 27,in copyfileobj buf = fsrc.read(length) IOError: [Errno 5] Input/output error 如何避免中止程序的执行并重新尝试复制过程? 我正在使用的代码已经通过检查filesize来检查文件是否完全被复制: def check_file(file,size=0): if not os.path.exists(file): return False if (size != 0 and os.path.getsize(file) != size): return False return True while (check_file(rempdg,self._ndays*130160640) is False): shutil.copy2(locpdg,rempdg) 解决方法
哪个区块出错?只需在它周围包裹一个
try/except:
def check_file(file,size=0): try: if not os.path.exists(file): return False if (size != 0 and os.path.getsize(file) != size): return False return True except IOError: return False # or True,whatever your default is while (check_file(rempdg,self._ndays*130160640) is False): try: shutil.copy2(locpdg,rempdg) except IOError: pass # ignore the IOError and keep going (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |