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
🌐
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
🌐
WMI
timgolden.me.uk › pywin32-docs › win32event.html
Module win32event - Tim Golden
Contents | Python for Win32 Extensions Help > Win32 API > Modules > win32event
Discussions

Python ModuleNotFoundError: No module named 'win32event' - Stack Overflow
in my Python Script there is an ERROR with the line import win32events I still installed the package pypiwin32 (with pip install pypiwin32) but it seems that this is nor the right package. Does som... More on stackoverflow.com
🌐 stackoverflow.com
How to install “win32event” module package from pypi # ERROR “pip install win32event” is not available. Thanks!
How to install “win32event” ... install win32event” is not available. Thanks!#16 ... Traceback (most recent call last): File "main.py", line 1, in from gui.main_gui import * File "D:\GitDownload\wos_crawler\wos_crawler\gui\main_gui.py", line 6, in import qt5reactor File "C:\Users\chunweizhu\AppData\Local\Programs\Python\Python37\... More on github.com
🌐 github.com
1
August 12, 2020
python - Create a Windows Event listener with win32evtlog - Stack Overflow
I am trying to develop a listener for the Windows event log. It should wait until anything new is added and when this happens it should catch the new event and pass it as an object so I can create a handler. I have found some things online but nothing has worked so far. I am using win32evtlog and ... More on stackoverflow.com
🌐 stackoverflow.com
ImportError: DLL load failed while importing win32event: The specified module could not be found.
I just installed Python 3.8.0 32-bit, then installed a few modules including pywin32 using pip. When I try "import win32event", I get the following error: Python 3.8.0 (tags/v3.8.0:fa919f... More on github.com
🌐 github.com
32
October 23, 2019
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.
🌐
PEAK-System
forum.peak-system.com › viewtopic.php
Python win32 event in different processes - PEAK-System Forum
PythonMain.PNG (35.27 KiB) Viewed 12396 times I also wrote a simple sample which has the same behavior: Pyhton.PNG (42.03 KiB) Viewed 12396 times the code used is this: ... from PCANBasic import * ## PCAN-Basic library import import threading ## Threading-based Timer library import win32event ## Windows Events # Instanciating the DLL PCANBasic_Object = PCANBasic() # Constants - adjust these as required # Globals g_pcanHandle = PCAN_NONEBUS g_Terminated = False g_readThread = None g_receiveEventObject = None def ConfigureChannel(channelToConnect): global g_receiveEventObject result = PCANBasic_Object.Initialize(channelToConnect, PCAN_BAUD_500K) if (result == PCAN_ERROR_OK): g_receiveEventObject = win32event.CreateEvent(None, 0, 0, None) # Configures the Receive-Event.
🌐
ProgramCreek
programcreek.com › python › example › 98749 › win32event.CreateEvent
Python Examples of win32event.CreateEvent
""" interp = win32com.client.Dispatch("Python.Interpreter") events = [] threads = [] for i in range(numThreads): hEvent = win32event.CreateEvent(None, 0, 0, None) events.append(hEvent) interpStream = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, interp._oleobj_) t = threading.Thread(target=self._testInterpInThread, args=(hEvent, interpStream)) t.setDaemon(1) # so errors dont cause shutdown hang t.start() threads.append(t) interp = None return threads, events # # NOTE - this doesnt quite work - Im not even sure it should, but Greg reckons # you should be able to avoid the marshal per thread!
🌐
ProgramCreek
programcreek.com › python › example › 5729 › win32event.SetEvent
Python Examples of win32event.SetEvent
""" results = [] def check(ignored): results.append(isInIOThread()) reactor.stop() reactor = self.buildReactor() event = win32event.CreateEvent(None, False, False, None) finished = Deferred() listener = Listener(finished) finished.addCallback(check) reactor.addEvent(event, listener, 'occurred') reactor.callWhenRunning(win32event.SetEvent, event) self.runReactor(reactor) self.assertTrue(listener.success) self.assertEqual([True], results)
Find elsewhere
🌐
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, but exactly what signaled means depends on the object.
Authors   Andy RobinsonMark Hammond
Published   2000
Pages   672
🌐
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
🌐
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.
🌐
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 ()
🌐
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
🌐
GitHub
github.com › tomleung1996 › wos_crawler › issues › 16
How to install “win32event” module package from pypi # ERROR “pip install win32event” is not available. Thanks! · Issue #16 · tomleung1996/wos_crawler
August 12, 2020 - pip install win32event Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple ERROR: Could not find a version that satisfies the requirement win32event (from versions: none) ERROR: No matching distribution found for win32event WARNING: You are using pip version 20.1.1; however, version 20.2.2 is available. You should consider upgrading via the 'c:\users\chunweizhu\appdata\local\programs\python\python37\python.exe -m pip install --upgrade pip' command.
Author   tomleung1996
🌐
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
🌐
Stack Overflow
stackoverflow.com › questions › 73050212 › create-a-windows-event-listener-with-win32evtlog
python - Create a Windows Event listener with win32evtlog - Stack Overflow
import win32evtlog import win32event server = 'localhost' # name of the target computer to get event logs logtype = 'Application' # 'Application' # 'Security' hand = win32evtlog.OpenEventLog(server,logtype) flags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ total = win32evtlog.GetNumberOfEventLogRecords(hand) print(total) h_evt = win32event.CreateEvent(None, 1, 0, "evt0") for x in range(10): notify = win32evtlog.NotifyChangeEventLog(hand, h_evt) wait_result = win32event.WaitForSingleObject(h_evt, win32event.INFINITE) print("notify", notify)
🌐
GitHub
github.com › mhammond › pywin32 › issues › 1431
ImportError: DLL load failed while importing win32event: The specified module could not be found. · Issue #1431 · mhammond/pywin32
October 23, 2019 - I just installed Python 3.8.0 32-bit, then installed a few modules including pywin32 using pip. When I try "import win32event", I get the following error: Python 3.8.0 (tags/v3.8.0:fa919f...
Author   mhammond
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

🌐
WMI
timgolden.me.uk › pywin32-docs › win32event__OpenEvent_meth.html
win32event.OpenEvent - Tim Golden
access flag - one of win32event::EVENT_ALL_ACCESS , win32event::EVENT_MODIFY_STATE , or (NT only) win32event::SYNCHRONIZE
🌐
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