تجنب خروج البرنامج على خطأ الإدخال / الإخراج

StackOverflow https://stackoverflow.com/questions/1254292

  •  12-09-2019
  •  | 
  •  

سؤال

لدي برنامج نصي 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)
هل كانت مفيدة؟

المحلول

الكتلة التي تعطي الخطأ؟ فقط التفاف أ حاول / باستثناء حولها:

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

نصائح أخرى

يمكنك استخدام

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

للقبض على الأخطاء وعلاجها

إلقاء نظرة على هذه

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top