XD blog

blog page

pywin32


2014-07-01 Pywin32 does not find its DLL

I recently needed to install pywin32 because of nbconvert. However, when importing win32api, it produces an exception (unable to find some DLL). To fix it, the following path <python>Lib/site-packages/pywin32_system32 must be added to environment variable PATH. But I did not want to do that but I'm using several Python version at the same time so I needed to fix it while running my script which I did below.

def import_pywin32():
    """
    For the module ``pywin32``,
    this function tries to add the path to the DLL to ``PATH``
    before throwing the exception: 
    ``DLL load failed: The specified module could not be found``.
    """
    try:
        import win32com
    except ImportError as e :
        if "DLL load failed:" in str(e):
            import os,sys
            path = os.path.join(os.path.split(sys.executable)[0], "Lib","site-packages","pywin32_system32")
            os.environ["PATH"] = os.environ["PATH"] + ";" + path
            try:
                import win32com
            except ImportError as ee :
                dll = os.listdir(path)
                dll = [os.path.join(path,_) for _ in dll if "dll" in _]
                raise ImportError("some DLL must be copied:\n" + "\n".join(dll)) from e
        else :
            raise e

I hope I'll remember I foudn a way to fix it next time I run into the same exception.


Xavier Dupré