Python - pythoncom.com_error handling in Python 3.2.2
Asked Answered
B

2

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!

Belgian answered 8/2, 2012 at 23:42 Comment(0)
O
8

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

Omsk answered 8/2, 2012 at 23:59 Comment(1)
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!Belgian
H
0

I use this structure (Python 3.5) --

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

Hid answered 10/1, 2018 at 23:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.