I think it does nothing. It's in the pywin32 service examples and has been for a good 10 years, but as far as I can tell, no such event is used by the library internally. win32event.SetEvent is supposed to get one thread (in win32event.CreateEvent(None,0,0,None) the first zero means the event will auto-reset as soon as a thread stops waiting, so it's really one thread) waiting for that event to continue, but unless I'm missing something with how services work, nothing ever waits for that event to be fired, so it won't do anything.

Same goes for socket.setdefaulttimeout(60), really, I think someone just forgot to remove it at one point before posting to stackoverflow, and with everyone building on top of what everyone else without, nobody knows why it's there anymore and nobody has ever dared to check. You can just remove the whole __init__ function.


EDIT: See the example from this question

import win32serviceutil 
import win32service 
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "SmallestPythonService"
    _svc_display_name_ = "display service"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

if __name__=='__main__':
    win32serviceutil.HandleCommandLine(SmallestPythonService)

Seems like it's usually meant so you can have an example service that runs until it's stopped.

Answer from VLRoyrenn on Stack Overflow
🌐
WMI
timgolden.me.uk › pywin32-docs › win32event.html
Module win32event - Tim Golden
Contents | Python for Win32 Extensions Help > Win32 API > Modules > win32event
🌐
GitHub
github.com › mhammond › pywin32 › blob › main › win32 › src › win32event.i
pywin32/win32/src/win32event.i at main · mhammond/pywin32
%module win32event // A module which provides an interface to the win32 event/wait API · · %include "typemaps.i" %include "pywin32.i" · %typedef void *NULL_ONLY · · %typemap(python,in) NULL_ONLY { if ($source != Py_None) { ...
Author   mhammond
🌐
ProgramCreek
programcreek.com › python › example › 98749 › win32event.CreateEvent
Python Examples of win32event.CreateEvent
def subscribe_and_yield_events(channel, query="*"): #SUBSCRIBE h = win32event.CreateEvent(None, 0, 0, None) s = win32evtlog.EvtSubscribe(channel, win32evtlog.EvtSubscribeToFutureEvents, SignalEvent=h, Query=query) #LOOP while True: while True: events = win32evtlog.EvtNext(s, 10) if len(events) == 0: break for event in events: raw_xml = win32evtlog.EvtRender(event, win32evtlog.EvtRenderEventXml) er = LogEvent(raw_xml, source_os=detect_current_os()) if er.is_valid(): yield er else: print("[ERROR] Parsing error") while True: #print('waiting...') w = win32event.WaitForSingleObjectEx(h, 200, True)
🌐
Chrisumbel
chrisumbel.com › article › windows_services_in_python
Windows Services in Python – Chris Umbel
June 26, 2022 - import win32service import win32serviceutil import win32event class PySvc(win32serviceutil.ServiceFramework): # you can NET START/STOP the service by the following name _svc_name_ = \"PySvc\" # this text shows up as the service name in the Service # Control Manager (SCM) _svc_display_name_ = \"Python Test Service\" # this text shows up as the description in the SCM _svc_description_ = \"This service writes stuff to a file\" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self,args) # create an event to listen for stop requests on self.hWaitStop = win32event.CreateEvent(Non
🌐
WMI
timgolden.me.uk › pywin32-docs › contents.html
PyWin32 Documentation - Tim Golden
win32event · CancelWaitableTimer · CreateEvent · CreateMutex · CreateSemaphore · CreateWaitableTimer · MsgWaitForMultipleObjects · MsgWaitForMultipleObjectsEx · OpenEvent · OpenMutex · OpenSemaphore · OpenWaitableTimer · PulseEvent · ReleaseMutex ·
Top answer
1 of 1
2

I think it does nothing. It's in the pywin32 service examples and has been for a good 10 years, but as far as I can tell, no such event is used by the library internally. win32event.SetEvent is supposed to get one thread (in win32event.CreateEvent(None,0,0,None) the first zero means the event will auto-reset as soon as a thread stops waiting, so it's really one thread) waiting for that event to continue, but unless I'm missing something with how services work, nothing ever waits for that event to be fired, so it won't do anything.

Same goes for socket.setdefaulttimeout(60), really, I think someone just forgot to remove it at one point before posting to stackoverflow, and with everyone building on top of what everyone else without, nobody knows why it's there anymore and nobody has ever dared to check. You can just remove the whole __init__ function.


EDIT: See the example from this question

import win32serviceutil 
import win32service 
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "SmallestPythonService"
    _svc_display_name_ = "display service"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

if __name__=='__main__':
    win32serviceutil.HandleCommandLine(SmallestPythonService)

Seems like it's usually meant so you can have an example service that runs until it's stopped.

🌐
Program Creek
programcreek.com › python › index › 255 › win32event
Python Module: win32event
This page shows the popular functions and classes defined in the win32event module. The items are ordered by their popularity in 40,000 open source Python projects.
🌐
WMI
timgolden.me.uk › pywin32-docs › win32event__OpenEvent_meth.html
win32event.OpenEvent - Tim Golden
Contents | Python for Win32 Extensions Help > Win32 API > Modules > win32event > OpenEvent
🌐
Brian3johnson
brian3johnson.github.io › pywin32 › win32 › event.html
Windows NT Eventlog — pywin32 305 documentation - GitHub …
''' regexp=re.compile('(.*)\s(.*)') #store result in site reg_result=regexp.search(evt_date) date=reg_result.group(1) the_time=reg_result.group(2) (mon,day,yr)=map(lambda x: string.atoi(x),string.split(date,'/')) (hr,min,sec)=map(lambda x: string.atoi(x),string.split(the_time,':')) tup=[yr,mon,day,hr,min,sec,0,0,0] sec=time.mktime(tup) return sec ####Main program #initialize variables flags = win32evtlog.EVENTLOG_BACKWARDS_READ|\ win32evtlog.EVENTLOG_SEQUENTIAL_READ #This dict converts the event type into a human readable form evt_dict={win32con.EVENTLOG_AUDIT_FAILURE:'EVENTLOG_AUDIT_FAILURE',
Find elsewhere
🌐
Readthedocs
python-can.readthedocs.io › en › stable › _modules › can › broadcastmanager.html
can.broadcastmanager - python-can 4.6.1 documentation
The main entry point to these classes ... -> None: import pywintypes # noqa: PLC0415 # pylint: disable=import-outside-toplevel,import-error import win32event # noqa: PLC0415 # pylint: disable=import-outside-toplevel,import-error self.pywintypes = pywintypes self.win32event ...
🌐
WMI
timgolden.me.uk › python › events.html
Events - Tim Golden's Python Stuff: wmi
import mmap import events import common shared_memory = mmap.mmap (0, common.SHARED_MEMORY_SIZE, common.SHARED_MEMORY_NAME) ready_to_consume_event = events.Win32Event (common.READY_TO_CONSUME) finished_producing_event = events.Win32Event (common.FINISHED_PRODUCING) line_number = 0 while 1: ready_to_consume_event.wait () shared_memory.write ("This is line %d\n" % line_number) line_number += 1 finished_producing_event.set ()
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch06s10.html
Processing Windows Messages Using MsgWaitForMultipleObjects - Python Cookbook [Book]
July 19, 2002 - import win32event import pythoncom TIMEOUT = 200 # ms StopEvent = win32event.CreateEvent(None, 0, 0, None) OtherEvent = win32event.CreateEvent(None, 0, 0, None) class myCoolApp: def OnQuit(self): if areYouSure( ): win32event.SetEvent(StopEvent) # Exit msg pump def _MessagePump( ): waitables = StopEvent, OtherEvent while 1: rc = win32event.MsgWaitForMultipleObjects( waitables, 0, # Wait for all = false, so it waits for anyone TIMEOUT, # (or win32event.INFINITE) win32event.QS_ALLEVENTS) # Accepts all input # You can call a function here, if it doesn't take too long.
Authors   Alex MartelliDavid Ascher
Published   2002
Pages   608
🌐
WMI
timgolden.me.uk › pywin32-docs › win32event__CreateEvent_meth.html
win32event::CreateEvent - Tim Golden
Contents | Python for Win32 Extensions Help > Win32 API > Modules > win32event > CreateEvent
🌐
O'Reilly
oreilly.com › library › view › python-programming-on › 1565926218 › apds02s02.html
D.2.2. win32event Module - Python Programming On Win32 [Book]
January 24, 2000 - There are three functions exposed by win32event that wait for Win32 objects: WaitForSingleObject(), WaitForMultipleObjects(), and MsgWaitFor-MultipleObjects(). Each of these functions allow you to wait for one or more handles to become signaled, ...
Authors   Andy RobinsonMark Hammond
Published   2000
Pages   672
🌐
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. See CHANGES.md for recent notable changes. adodbapi's documentation can be found in: adodbapi/readme.txt
      » pip install pywin32
    
Published   Jun 04, 2026
Version   312
Top answer
1 of 1
11

you can find plenty of demos related to the winapi in your C:\PythonXX\Lib\site-packages\win32\Demos folder. In this folder you'll find a script named eventLogDemo.py. There you can see how to use win32evtlog module. Just start this script with eventLogDemo.py -v and you will get prints from your Windows event log with logtype Application.

In case you can't find this script:

import win32evtlog
import win32api
import win32con
import win32security # To translate NT Sids to account names.

import win32evtlogutil

def ReadLog(computer, logType="Application", dumpEachRecord = 0):
    # read the entire log back.
    h=win32evtlog.OpenEventLog(computer, logType)
    numRecords = win32evtlog.GetNumberOfEventLogRecords(h)
#       print "There are %d records" % numRecords

    num=0
    while 1:
        objects = win32evtlog.ReadEventLog(h, win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ, 0)
        if not objects:
            break
        for object in objects:
            # get it for testing purposes, but dont print it.
            msg = win32evtlogutil.SafeFormatMessage(object, logType)
            if object.Sid is not None:
                try:
                    domain, user, typ = win32security.LookupAccountSid(computer, object.Sid)
                    sidDesc = "%s/%s" % (domain, user)
                except win32security.error:
                    sidDesc = str(object.Sid)
                user_desc = "Event associated with user %s" % (sidDesc,)
            else:
                user_desc = None
            if dumpEachRecord:
                print "Event record from %r generated at %s" % (object.SourceName, object.TimeGenerated.Format())
                if user_desc:
                    print user_desc
                try:
                    print msg
                except UnicodeError:
                    print "(unicode error printing message: repr() follows...)"
                    print repr(msg)

        num = num + len(objects)

    if numRecords == num:
        print "Successfully read all", numRecords, "records"
    else:
        print "Couldn't get all records - reported %d, but found %d" % (numRecords, num)
        print "(Note that some other app may have written records while we were running!)"
    win32evtlog.CloseEventLog(h)

def usage():
    print "Writes an event to the event log."
    print "-w : Dont write any test records."
    print "-r : Dont read the event log"
    print "-c : computerName : Process the log on the specified computer"
    print "-v : Verbose"
    print "-t : LogType - Use the specified log - default = 'Application'"


def test():
    # check if running on Windows NT, if not, display notice and terminate
    if win32api.GetVersion() & 0x80000000:
        print "This sample only runs on NT"
        return

    import sys, getopt
    opts, args = getopt.getopt(sys.argv[1:], "rwh?c:t:v")
    computer = None
    do_read = do_write = 1

    logType = "Application"
    verbose = 0

    if len(args)>0:
        print "Invalid args"
        usage()
        return 1
    for opt, val in opts:
        if opt == '-t':
            logType = val
        if opt == '-c':
            computer = val
        if opt in ['-h', '-?']:
            usage()
            return
        if opt=='-r':
            do_read = 0
        if opt=='-w':
            do_write = 0
        if opt=='-v':
            verbose = verbose + 1
    if do_write:
        ph=win32api.GetCurrentProcess()
        th = win32security.OpenProcessToken(ph,win32con.TOKEN_READ)
        my_sid = win32security.GetTokenInformation(th,win32security.TokenUser)[0]

        win32evtlogutil.ReportEvent(logType, 2,
            strings=["The message text for event 2","Another insert"],
            data = "Raw\0Data".encode("ascii"), sid = my_sid)
        win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_WARNING_TYPE,
            strings=["A warning","An even more dire warning"],
            data = "Raw\0Data".encode("ascii"), sid = my_sid)
        win32evtlogutil.ReportEvent(logType, 1, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE,
            strings=["An info","Too much info"],
            data = "Raw\0Data".encode("ascii"), sid = my_sid)
        print("Successfully wrote 3 records to the log")

    if do_read:
        ReadLog(computer, logType, verbose > 0)

if __name__=='__main__':
    test()

I hope this script fits your needs

🌐
PEAK-System
forum.peak-system.com › viewtopic.php
Python win32 event in different processes - PEAK-System Forum
... stsResult = self.m_objPCANBasic.SetValue(self.m_PcanHandle_read, PCAN_RECEIVE_EVENT, self.m_ReceiveEvent) if stsResult != PCAN_ERROR_OK: print ("Error: " + self.GetFormatedError(stsResult)) else: self.event_start_write.set() endTimestamp = millis() + self.test.delay self.count = 0 while True: if win32event.WaitForSingleObject(self.m_ReceiveEvent, self.test.delay) == win32event.WAIT_OBJECT_0: if not self.max_delay: if self.ReadMessages(): break else: self.ReadMessages() if millis() > endTimestamp: break self.m_objPCANBasic.SetValue(self.m_PcanHandle_read, PCAN_RECEIVE_EVENT, 0) ...
🌐
ProcessLibrary
processlibrary.com › en › directory › files › win32event › 406045
win32event.pyd - What is win32event.pyd?
The win32event.pyd is an executable file on your computer's hard drive. This file contains machine code. If you start the software PyWin32 on your PC, the commands contained in win32event.pyd will be executed on your PC.
🌐
YouTube
youtube.com › watch
Using Events in Python Win32 | Part 1 - YouTube
Inside the VBA object model, we have access to events that allow us to execute VBA code when a user triggers an event. The same events can be accessed from t...
Published   May 11, 2019
🌐
GitHub
github.com › Travis-Sun › pywin32 › blob › master › win32 › help › event.d
pywin32/win32/help/event.d at master · Travis-Sun/pywin32
The library of primary importance is win32evtlog. With it you can ... @topic Windows NT Eventlog and Threading |Python's threading to manage access access to many Eventlogs
Author   Travis-Sun