避免在I/O错误时程序退出

4 投票
2 回答
3033 浏览
提问于 2025-04-15 13:30

我有一个Python脚本,里面大量使用了shutil.copy2这个功能。因为我用它来通过网络复制文件,所以经常会遇到输入输出错误,这导致我的程序执行中断:

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

我该怎么做才能避免程序中断,而是让它重新尝试复制文件呢?

我现在的代码已经通过检查文件大小来确认文件是否真的复制完整:

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)

2 个回答

6

你可以使用

try:
    ...
except IOError as err:
    ...

来捕捉错误并处理它们。

可以看看这个链接

8

哪个代码块出错了?只需要在它周围加上一个 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

撰写回答