Python - pythoncom.com_error handling in Python 3.2.2

user1198460 picture user1198460 · Feb 9, 2012 · Viewed 13.4k times · Source

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!

Answer

DSM picture DSM · Feb 9, 2012

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.]