3

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!

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that, worked brilliantly. What I really wanted was a particular part of what eventually becomes exc in your code above. I used: except pythoncom.com_error as error: hr,msg,exc,arg = error.args errorMessage = exc[2] Thanks again!
0

I use this structure (Python 3.5) --

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.