You get the AttributeError: __enter__ error because xl.workbooks.open is not a context manager, and so it doesn't support the with statement.

If you want to use a with statement in your code you can use the closing function from the contextlib module in the standard library, like this:

from contextlib import closing

def wb_ref(file):
    xl.DisplayAlerts = False
    with closing(xl.workbooks.open(file)) as wb:
        wb.RefreshAll()
        wb.Save()

contextlib.closing will automatically call close on the object that is passed to it when the code in the with block has completed execution.

Answer from snakecharmerb on Stack Overflow
🌐
WMI
timgolden.me.uk › pywin32-docs › html › com › win32com › HTML › QuickStartClientCom.html
Quick Start to Client side COM and Python - Tim Golden
The functions GetModuleForCLSID and GetModuleForProgID both return Python module objects that you can use in your code. See the docstrings in the gencache code for more details. ... Run 'win32com\client\makepy.py' (eg, run it from the command window, or double-click on it) and a list will be ...
🌐
ProgramCreek
programcreek.com › python › example › 63229 › win32com.client
Python Examples of win32com.client
"""Given a COM prog_id, return an object that is using makepy support, building if necessary""" disp = win32com.client.Dispatch(prog_id) if not disp.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it. try: ti = disp._oleobj_.GetTypeInfo() disp_clsid = ti.GetTypeAttr()[0] tlb, index = ti.GetContainingTypeLib() tla = tlb.GetLibAttr() mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand) GetModuleForCLSID(disp_clsid) # Get the class from the module. import CLSIDToClass disp_class = CLSIDToClass.GetClass(str(disp_clsid)) disp = disp_class(disp._oleobj_) except
Discussions

pywin32 - Python win32com.client and "with" statement - Stack Overflow
Good afternoon, I am writing some ETL scripts with Python, and am currently using win32com.client to open and refresh some data connections in Excel. My question is this: should I be using a with More on stackoverflow.com
🌐 stackoverflow.com
python - List all methods in COMobject - Stack Overflow
This worked for me on Python 2.7 - I just had to change the {method} syntax in the print statements to make it compatible. 2019-02-13T02:48:56.543Z+00:00 ... This is a good answer but note that this will only work with the application object. If you want further objects and to stick with win32com.client... More on stackoverflow.com
🌐 stackoverflow.com
python - What exactly does win32com.client.Dispatch("WScript.Shell")? - Stack Overflow
In order to find wether it comes ... about win32com.client and what really represents WScript.Shell ... As we discussed previously, automation objects are COM objects that expose methods and properties using the IDispatch interface. So how do we use these objects from Python... More on stackoverflow.com
🌐 stackoverflow.com
Win32com.client
Hi everyone I am trying to create a log using win32com.client module - I have installed the module with the following command - pip install pywin32 - Installation was successful. However when I tried to run the below script I get the following error. The Python Win32 extensions for NT (service, ... More on discuss.python.org
🌐 discuss.python.org
11
0
June 18, 2022
🌐
Reddit
reddit.com › r/learnpython › what do you use win32com for?
r/learnpython on Reddit: What do you use Win32com for?
June 4, 2020 -

(I've used python for a couple of years, but am no means an expert.)

I saw the Win32com package in a stackoverflow question, so I started poking around to learn more about it. It looks like you can use it to manipulate Excel and create text-to-speech. But the examples and documentation that I've found are few and far between.

I was curious to know what members of this community use Win32com for.

And are there any good tutorials/YouTube videos on how to use it?

🌐
Practical Business Python
pbpython.com › windows-com.html
Automating Windows Applications Using COM - Practical Business Python
July 2, 2018 - This resource has many more details on how to use python on Windows for automation and other administration tasks. All of these applications start with similar imports and process for activating an application. Here is a very short example of opening up Excel: import win32com.client as win32 excel = win32.gencache.EnsureDispatch('Excel.Application') excel.Visible = True _ = input("Press ENTER to quit:") excel.Application.Quit()
🌐
Cesarkallas
cesarkallas.net › arquivos › apostilas › python › doc › Python Programming on Win32_ Chapter 12 Advanced Python and COM.pdf pdf
Python Programming on Win32: Chapter 12 Advanced Python and COM
To force the MakePy process, the win32com.client.gencache module is used. This module · contains the code that manages the directory of MakePy-generated source files: the generated · cache, or gencache. There are a number of useful functions in this module, and you are
🌐
WMI
timgolden.me.uk › pywin32-docs › contents.html
PyWin32 Documentation - Tim Golden
ADSI Python · Active Directory · Important notes about COM currency support changes · win32com documentation index · win32com readme · Modules · adsi · ADsBuildEnumerator · ADsEnumerateNext · ADsGetLastError · ADsGetObject · ADsOpenObject · DSOP_SCOPE_INIT_INFOs ·
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › convert-text-speech-python-using-win32com-client
Convert Text to Speech in Python using win32com.client | GeeksforGeeks
September 29, 2022 - # Python program to convert # text to speech # import the required module from text to speech conversion import win32com.client # Calling the Dispatch method of the module which # interact with Microsoft Speech SDK to speak # the given input from the keyboard speaker = win32com.client.Dispatch("SAPI.SpVoice") while 1: print("Enter the word you want to speak it out by computer") s = input() speaker.Speak(s) # To stop the program press # CTRL + Z Input: ... Let us see how to read a PDF that is converting a textual PDF file into audio.Packages Used:pyttsx3: It is a Python library for Text to Speech. It has many functions which will help the machine to communicate with us.
🌐
GitHub
github.com › mhammond › pywin32 › blob › main › com › win32com › client › __init__.py
pywin32/com/win32com/client/__init__.py at main · mhammond/pywin32
the getevents() function yourself, you must make your own arrangements · to manage this circular reference issue. · Beware of creating Python circular references: this will happen if your · handler has a reference to an object that has a reference back to · the event source. Call the 'close' method to break the chain. · Example: · >>>win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}',0,1,1) <module 'win32com.gen_py.....
Author   mhammond
🌐
O'Reilly
oreilly.com › library › view › python-programming-on › 1565926218 › ch12s02.html
12.2. Python and COM - Python Programming On Win32 [Book]
January 24, 2000 - As in most Python packages, win32com has a number of subpackages; win32com.client is concerned with supporting client-side COM (i.e., helping to call COM interfaces), and win32com.server is concerned with helping Python programs use server-side ...
Authors   Andy RobinsonMark Hammond
Published   2000
Pages   672
🌐
WMI
timgolden.me.uk › pywin32-docs › html › com › win32com › HTML › package.html
The win32com package - Tim Golden
Some of the modules are described below: win32com.pythoncom - core C++ support. This module is rarely used directly by programmers - instead the other "helper" module are used, which themselves draw on the core pythoncom services. win32com.client package Support for COM clients used by Python.
🌐
Narkive
comp.lang.python.narkive.com › RgTUhULI › specification-for-win32com-client-package
Specification for win32com.client package
It can be used to generate a proxy Python module for an existing COM package, eg: <code> from win32com.client import gencache xl = gencache.EnsureDispatch ("Excel.Application") # # Behind the scenes this has called makepy to generate # a module which on my machine is under # c:\python24\li...
🌐
CodeRivers
coderivers.org › blog › python-win32com
Python win32com: A Comprehensive Guide - CodeRivers
February 22, 2026 - The gencache.EnsureDispatch function is similar but it also generates a cache of the COM object's type information, which can improve performance in some cases. Once you have connected to a COM object, you can access its properties and methods. For example, to create a new document in Word: import win32com.client word_app = win32com.client.Dispatch("Word.Application") # Create a new document new_doc = word_app.Documents.Add() # Add some text to the document new_doc.Content.Text = "This is some sample text."
🌐
PyPI
pypi.org › project › pywin32
pywin32 · PyPI
This is the readme for the Python for Win32 (pywin32) extensions, which provides access to many of the Windows APIs from Python, including COM support.
      » pip install pywin32
    
Published   Jun 04, 2026
Version   312
Top answer
1 of 3
18

For those who find the accepted answer not working (look here for the reasons) - there's still a way to get objects having a _prop_map_get_ attribute (a dict that holds object's fields as keys). You just have to create the main app object with win32com.client.gencache.EnsureDispatch().

Here's a convenience function I wrote that lists fields and methods of a passed COM object created that way:

from inspect import getmembers


def print_members(obj, obj_name="placeholder_name"):
    """Print members of given COM object"""
    try:
        fields = list(obj._prop_map_get_.keys())
    except AttributeError:
        print("Object has no attribute '_prop_map_get_'")
        print("Check if the initial COM object was created with"
              "'win32com.client.gencache.EnsureDispatch()'")
        raise
    methods = [m[0] for m in getmembers(obj) if (not m[0].startswith("_")
                                                 and "clsid" not in m[0].lower())]

    if len(fields) + len(methods) > 0:
        print("Members of '{}' ({}):".format(obj_name, obj))
    else:
        raise ValueError("Object has no members to print")

    print("\tFields:")
    if fields:
        for field in fields:
            print(f"\t\t{field}")
    else:
        print("\t\tObject has no fields to print")

    print("\tMethods:")
    if methods:
        for method in methods:
            print(f"\t\t{method}")
    else:
        print("\t\tObject has no methods to print")

For an Excel object created with win32com.client.gencache.EnsureDispatch("Excel.Application") its output would be:

Members of 'Excel.Application' (Microsoft Excel):
    Fields:
        ActiveCell
        ActiveChart
        ActiveDialog
        ActiveEncryptionSession
        ...
        Workbooks
        WorksheetFunction
        Worksheets
        _Default
    Methods:
        ActivateMicrosoftApp
        AddChartAutoFormat
        AddCustomList
        Calculate
        ...
        Union
        Volatile
        Wait
2 of 3
9

Just found how to get most of the methods:

Here's how:

import win32com.client
import pythoncom

ProgID = "someProgramID"
com_object = win32com.client.Dispatch(ProgID)

for key in dir(com_object):
    method = getattr(com_object,key)
    if str(type(method)) == "<type 'instance'>":
        print key
        for sub_method in dir(method):
            if not sub_method.startswith("_") and not "clsid" in sub_method.lower():
                print "\t"+sub_method
    else:
        print "\t",method

Here's a exemple output with ProgID = "Foobar2000.Application.0.7"

Output:

Playlists
    Add
    GetSortedTracks
    GetTracks
    Item
    Load
    Move
    Remove
    Save
Name
    foobar2000 v1.1.13
ApplicationPath
    C:\Program Files (x86)\foobar2000\foobar2000.exe
MediaLibrary
    GetSortedTracks
    GetTracks
    Rescan
Minimized
    True
Playback
    FormatTitle
    FormatTitleEx
    Next
    Pause
    Previous
    Random
    Seek
    SeekRelative
    Start
    Stop
ProfilePath
    file://C:\Users\user\AppData\Roaming\foobar2000
🌐
Brian3johnson
brian3johnson.github.io › pywin32 › com › QuickStartClientCom.html
Quick Start to Client side COM and Python — pywin32 305 documentation
Hopefully, the answer is you shouldn’t need to. All generated file support is generally available directly via win32com.client.Dispatch and win32com.client.constants. But should you ever really need the Python module object, the win32com.client.gencache module has functions specifically for this.
🌐
Python.org
discuss.python.org › python help
Win32com.client - Python Help - Discussions on Python.org
June 18, 2022 - Hi everyone I am trying to create a log using win32com.client module - I have installed the module with the following command - pip install pywin32 - Installation was successful. However when I tried to run the below script I get the following error. The Python Win32 extensions for NT (service, ...
🌐
IQCode
iqcode.com › code › python › python-win32com
python win32com Code Example
February 22, 2022 - python win32com.client documentation win32com.client python 3 win32com.shell python win32com api python win32com python tutorial win32com.shell python3 win32com module python what is win32com.client in python win32com.client python pip win32com client python 3 documentation python win32com.client install python win32com linux python3 win32com python import win32com.client python win32com.client functions python module win32com win32com download python win32com in python win32com.client python install python winCOM32 the import win32com.client in python python win32com doc python package win32c