2011-06-13 4 views
0

Je suis en train d'ouvrir un fichier Excel en python utilisant COM, et en essayant d'attraper le fichier non trouvé erreur:Comment attraper une exception pywin32com sur les dossiers d'ouverture

J'ai d'abord essayé attraper le IOError:

try: 
    output = xl.Workbooks.Open(Params.workbookName) 
except IOError as reason: 
    print reason 
    exit() 

Mais COM ne soulève pas une erreur IO quand il a un problème de fichier non trouvé, au lieu qu'il soulève quelque chose appelé com_error:

com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u"'asdf.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.", u'C:\Program Files (x86)\Microsoft Office\Office12\1033\XLMAIN11.CHM', 0, -2146827284), None)

donc logiquement j'essayé ceci:

try: 
    output = xl.Workbooks.Open(Params.workbookName) 
except com_error as reason: 
    print reason 
    exit() 

mais ...

NameError: global name 'ComError' is not defined 

Répondre

1

Essayez:

from pythoncom import com_error 

et l'attraper dans votre bloc except

Questions connexes