Python - pythoncom.com_error handling in Python 3.2.2

半城伤御伤魂 提交于 2019-12-01 06:52:07

问题


I am using Python 3.2.2, and building a Tkinter interface to do some Active Directory updating. I am having trouble trying to handle pythoncom.com_error exceptions.

I grabbed some code from here: http://code.activestate.com/recipes/303345-create-an-account-in-ms-active-directory/

However, I use the following (straight from the above site) handle the exceptions raised:

except pythoncom.com_error,(hr,msg,exc,arg):

This code is consistent with many of the sites I have seen that handle these exceptions, however with Python 3.2.2, I get a syntax error if I include the comma after "pythoncom.com_error". If I remove the comma, the program starts, but then when the exception is raised, I get other exceptions because "hr", "msg" etc are not defined as global variables.

If I remove the comma and all of the bits in the brackets, then it all works well, except I can't see exactly what happens in the exception, which I want so I can pass through the actual error message from AD.

Does anyone know how to handle these pythoncom exceptions properly in Python 3.2.2?

Thanks in advance!


回答1:


You simply need to use the modern except-as syntax, I think:

import pythoncom
import win32com
import win32com.client

location = 'fred'
try:
    ad_obj=win32com.client.GetObject(location)
except pythoncom.com_error as error:
    print (error)
    print (vars(error))
    print (error.args)
    hr,msg,exc,arg = error.args

which produces

(-2147221020, 'Invalid syntax', None, None)
{'excepinfo': None, 'hresult': -2147221020, 'strerror': 'Invalid syntax', 'argerror': None}
(-2147221020, 'Invalid syntax', None, None)

for me [although I'm never sure whether the args order is really what it looks like, so I'd probably refer to the keys explicitly; someone else may know for sure.]




回答2:


I use this structure (Python 3.5) --

try: ... except Exception as e: print ("error in level argument", e) ... else: ...



来源:https://stackoverflow.com/questions/9203336/python-pythoncom-com-error-handling-in-python-3-2-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!