Skip to content

Instantly share code, notes, and snippets.

@rdapaz
Last active May 23, 2024 07:03
Show Gist options
  • Save rdapaz/63590adb94a46039ca4a10994dff9dbe to your computer and use it in GitHub Desktop.
Save rdapaz/63590adb94a46039ca4a10994dff9dbe to your computer and use it in GitHub Desktop.
Fix for module win32com.gen_py has no attribute 'CLSIDToPackageMap'
# If errors are found, do this
# clear contents of C:\Users\<username>\AppData\Local\Temp\gen_py
# that should fix it, to test it type
import win32com.client
app = win32com.client.gencache.EnsureDispatch('Word.Application')
app.Visible = True
@Ddedalus
Copy link

Ddedalus commented Feb 4, 2019

From PowerShell one can use:

 Remove-Item -path $env:LOCALAPPDATA\Temp\gen_py -recurse

@meGregV
Copy link

meGregV commented Feb 19, 2019

Directly in python:

from pathlib import Path
 try:
        xl = win32.gencache.EnsureDispatch('Excel.Application')
    except AttributeError:
        f_loc = r'C:\Users\<username>\AppData\Local\Temp\gen_py'
        for f in Path(f_loc):
            Path.unlink(f)
        Path.rmdir(f_loc)
        xl = win32.gencache.EnsureDispatch('Excel.Application')

@fossum
Copy link

fossum commented May 15, 2019

@VrunBert's code didnt work for me, but I think I came up with a good solution. Note: This code has been modified from my internal code.

try:
    xl = client.gencache.EnsureDispatch('Excel.Application')
except AttributeError:
    # Corner case dependencies.
    import os
    import re
    import sys
    import shutil
    # Remove cache and try again.
    MODULE_LIST = [m.__name__ for m in sys.modules.values()]
    for module in MODULE_LIST:
        if re.match(r'win32com\.gen_py\..+', module):
            del sys.modules[module]
    shutil.rmtree(os.path.join(os.environ.get('LOCALAPPDATA'), 'Temp', 'gen_py'))
    from win32com import client
    xl = client.gencache.EnsureDispatch('Excel.Application')

@vipwp
Copy link

vipwp commented May 17, 2019

From PowerShell one can use:

 Remove-Item -path $env:LOCALAPPDATA\Temp\gen_py -recurse

it's useful,thank you very much~

@PointedEars
Copy link

PointedEars commented Sep 5, 2019

@VrunBert's code didnt work for me, but I think I came up with a good solution. Note: This code has been modified from my internal code.

[…]
try:
    xl = client.gencache.EnsureDispatch('Excel.Application')
except AttributeError:
    […]
    # Remove cache and try again.
    MODULE_LIST = [m.__name__ for m in sys.modules.values()]
    for module in MODULE_LIST:
        if re.match(r'win32com\.gen_py\..+', module):
            del sys.modules[module]
    shutil.rmtree(os.path.join(os.environ.get('LOCALAPPDATA'), 'Temp', 'gen_py'))
    […]

Works like a charm, thank you very much 👍 :-)

@myidealab
Copy link

From PowerShell one can use:

 Remove-Item -path $env:LOCALAPPDATA\Temp\gen_py -recurse

Thanks @Ddedalus. Saved me a lot of time.

@sjlouis
Copy link

sjlouis commented Apr 14, 2020

Hi,

In my case, I also have to restart the computer. But why we have this problem? I use Python and win32com since a few years but this problem is recent, only a few months, and I got it several times on 3 different computers and several times on the same computer.

Thank you.

@soundmud
Copy link

soundmud commented Jul 8, 2020

In my case, the problem appeared just after installing the Zoom client. My unit tests were OK just before, and they broke shortly after (I run pytest-watch locally). Maybe it's just a coincidence though.

@monicalicareti
Copy link

monicalicareti commented Jul 22, 2020

OMG! Thank you for this fix!
I literally spent 3 days trying to find what's wrong in my code, even sent an email to Vector support to ask for help (my com client app is a Vector app).
This made the day for me! Much appreciated :)

@Kunj-97
Copy link

Kunj-97 commented Jul 27, 2020

Thanks this worked like a charm.

@snaddon
Copy link

snaddon commented Mar 19, 2021

I had this issue, but my solution ended up being reinstalling MS Office 365.

@francescosalvi
Copy link

🙏 thanks!

@robb666
Copy link

robb666 commented Apr 1, 2021

fossum <--- many thanks!

@mike-petrov
Copy link

In my case it turned out that gen_py was placed in a different folder, maybe this will help someone:

C:\Users\<username>\AppData\Local\Temp\2\gen_py

@sjlouis
Copy link

sjlouis commented Jun 6, 2021

And have you still the problem in this case ?

@mike-petrov
Copy link

No, I cleared the contents of C:\Users\<username>\AppData\Local\Temp\2\gen_py and the problem was fixed

@sjlouis
Copy link

sjlouis commented Jun 6, 2021

Yes, clear the content of \gen_py solves the problem but this problem occurs a lot of time and it's very annoying.

@broigol
Copy link

broigol commented Jul 16, 2021

From PowerShell one can use:

 Remove-Item -path $env:LOCALAPPDATA\Temp\gen_py -recurse

TKS!

@alkaline130
Copy link

alkaline130 commented Sep 27, 2021

I cleared the contents of C:\Users<username>\AppData\Local\Temp\gen_py and ran the below in Win10 command prompt

import win32com.client
app = win32com.client.gencache.EnsureDispatch('Word.Application')

but Word did not start. There was no error message. The command prompt just blinked for a few seconds before returning the usual ">>>"

Has anyone experience this before?

Same issue with Excel.Application

I am running:

Python` 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32

Further note: I uninstalled the 64 bit Python

Thanks sijlous.

2 days later: my issue is that I did not >>>app.Visible = True

Stupid me!

@sjlouis
Copy link

sjlouis commented Sep 27, 2021

After deleting the content of C:\Users\AppData\Local\Temp\gen_py, you have to restart the computer. Then you can launch in Python or Spyder :

`import win32com.client as win32
from win32com.client import constants, Dispatch

excel = win32.gencache.EnsureDispatch ("Excel.Application")
word = win32.gencache.EnsureDispatch("Word.Application")
`

@ceprio
Copy link

ceprio commented Oct 5, 2021

I modified @fossum code:

try:
    xl = client.gencache.EnsureDispatch('Excel.Application')
except AttributeError:
    # Corner case dependencies.
    import os
    import re
    import sys
    import shutil
    # Remove cache and try again.
    MODULE_LIST = [m.__name__ for m in sys.modules.values()]
    for module in MODULE_LIST:
        if re.match(r'win32com\.gen_py\..+', module):
            del sys.modules[module]
    shutil.rmtree(os.path.abspath(os.path.join(win32com.__gen_path__, '..')))
    from win32com import client
    xl = client.gencache.EnsureDispatch('Excel.Application')

shutil.rmtree(os.path.join(os.environ.get('LOCALAPPDATA'), 'Temp', 'gen_py')) did not work for me as the code is running on a server.

Better to use:
shutil.rmtree(os.path.abspath(win32com.__gen_path__+'/..'))

@amine-aboufirass
Copy link

amine-aboufirass commented Oct 29, 2021

@Ddedalus worked for me, thanks...

Anyone know what causes this? Seems rather unpredictable....

@nfa07
Copy link

nfa07 commented Mar 27, 2022

Depuis PowerShell on peut utiliser :

 Remove-Item -path $env:LOCALAPPDATA\Temp\gen_py -recurse

Thanks

@HeroOfStorm
Copy link

The following code will only delete the folder of the cache - it worked for me, but the better solution is "shutil" - earlier in this topic

try:
xl = gencache.EnsureDispatch('Excel.Application')
except AttributeError as ae:
error_message = str(ae)
if 'win32com.gen_py' in error_message:
start = error_message.find('win32com.gen_py.')+len('win32com.gen_py.')
tmp_em = error_message[start:]
end = tmp_em.find("'")
the_dir_to_remove = tmp_em[:end]
if the_dir_to_remove in os.listdir(win32com.gen_path):
win_gen_path_to_rm = win32com.gen_path+'\'+the_dir_to_remove
print("Removing: ", win_gen_path_to_rm)
recurcive_removal(win_gen_path_to_rm)
else:
print("unknown error of win32com")
else:
print("unknown error")
print(ae)

@amarines2605
Copy link

In My case, i had to reinstall office first in my case 64 bit
when i took the desicion to reinstall there were an error caused for AccessDatabaseEngine---(2007) 32 bit,
i had to uninstall Acess... first before i could reinstall, such thing was causing some sort of conflict or whatnot
,then # clear contents of C:\Users<username>\AppData\Local\Temp\gen_py
,then it work again

@jfthuong
Copy link

jfthuong commented May 31, 2023

Note that the folder gen_py with the associated python version could be retrieved directly from win32com.__gen_path__:

Therefore, we could have the following code:

import logging
import re
from pathlib import Path
from shutil import rmtree

from win32com import client, __gen_path__

try:
    word = client.gencache.EnsureDispatch("Word.Application")
except AttributeError as e:
    # Sometimes we might have to clean the cache to open
    m_failing_cache = re.search(r"win32com\.gen_py\.([\w\-]+)", str(e))
    if m_failing_cache:
        cache_folder_name = m_failing_cache.group(1)
        logging.warning(f"Cleaning cache for '{cache_folder_name}'")
        cache_folder = Path(__gen_path__).joinpath(cache_folder_name)
        rmtree(cache_folder)
        word = client.gencache.EnsureDispatch("Word.Application")
    else:
        raise

@jfthuong
Copy link

The following code will only delete the folder of the cache - it worked for me, but the better solution is "shutil" - earlier in this topic

try: xl = gencache.EnsureDispatch('Excel.Application') except AttributeError as ae: error_message = str(ae) if 'win32com.gen_py' in error_message: start = error_message.find('win32com.gen_py.')+len('win32com.gen_py.') tmp_em = error_message[start:] end = tmp_em.find("'") the_dir_to_remove = tmp_em[:end] if the_dir_to_remove in os.listdir(win32com.gen_path): win_gen_path_to_rm = win32com.gen_path+''+the_dir_to_remove print("Removing: ", win_gen_path_to_rm) recurcive_removal(win_gen_path_to_rm) else: print("unknown error of win32com") else: print("unknown error") print(ae)

@HeroOfStorm When putting code, it's better to put between triple backsticks with an optional language, like:

```python
... Your code
```

This will:

  • Ensure correct indenting
  • Avoid __gen_path__ being replaced by gen_path (with bold and without underscores)
  • Provide syntax Highlighting

@amarines2605
Copy link

Hi, in my case, sudenly, it happens again, i tried all metods showed here and no luck, in the end, i realized that my microsoft 365 apps for enterprise had beed updated few days ago in windows control panel, just right click, change, quick repair, and thats it, it worked again!!

regards

@CeejayMack
Copy link

@amarines2605 - I've deleted gen_py countless times as everyone seems to recommend... the quickfix for microsoft 365 was the piece I was missing. Thank you for the solution.

@d4ta4nalyst
Copy link

Remove-Item -path $env:LOCALAPPDATA\Temp\gen_py -recurse

work for me!!!!!!!!!!!! ty!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment