Python handling .net exceptions makes PyQt unable to use OLE
Question: I have a large PyQt4 based Python program. In some places it needs to be able
to control a piece of hardware for which the manufacturer provides a .net
interface. I need to be able to load the relevant library if it's available,
and ignore it otherwise.

If the library is not present, and I try and report the exception, then Qt
reports an OLE initialization error, and all drag-and-drop and copy/paste
functionality in my program fails.

Here is a minimal example:

    
    
    import clr
    import sys
    from PyQt4 import QtGui
    import logging
    logger = logging.getLogger(__name__)
    
    try:
        clr.AddReference('foo') #This doesn't exist
    except Exception as e:
        logger.info('Exception: {0}'.format(e))
    app = QtGui.QApplication(sys.argv)
    app.exec_()
    

This results in the Qt error:

    
    
    Qt: Could not initialize OLE (error 80010106)
    

The program runs, but whenever I try and copy/paste, I get:

    
    
    QClipboard::setMimeData: Failed to set data on clipboard ()
    

and drag-and-drop doesn't work at all.

If the library does exist, the code runs without a problem. Interestingly, if
I don't try and look at the exception, (i.e. replace the except block with
"pass"), the code also runs fine. Somehow, trying to see the exception messes
up the .net interface.

Is there a better way to check whether a library exists before trying to add
it as a reference? Is there any way to reset the .net connection before
running QApplication, to guarantee that this sort of thing doesn't happen in
the future? Any ideas why this problem happens?


Answer: There is a better way than try to `clr.AddReference()` \- the method is called
`clr.FindAssembly('DOT_NET_Assembly_Name')` which returns full path to
assembly or `None`.

