'Set up an event tracker on a WMI event. This function
returns an wmi_watcher which can be called to get the
next event::
c = wmi.WMI ()
raw_wql = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_Process\'"
watcher = c.watch_for (raw_wql=raw_wql)
while 1:
process_created = watcher ()
print process_created.Name
# or
watcher = c.watch_for (
notification_type="Creation",
wmi_class="Win32_Process",
delay_secs=2,
Name=\'calc.exe\'
calc_created = watcher ()
Now supports timeout on the call to watcher::
import pythoncom
import wmi
c = wmi.WMI (privileges=["Security"])
watcher1 = c.watch_for (
notification_type="Creation",
wmi_class="Win32_NTLogEvent",
Type="error"
watcher2 = c.watch_for (
notification_type="Creation",
wmi_class="Win32_NTLogEvent",
Type="warning"
while 1:
try:
error_log = watcher1 (500)
except wmi.x_wmi_timed_out:
pythoncom.PumpWaitingMessages ()
else:
print error_log
try:
warning_log = watcher2 (500)
except wmi.x_wmi_timed_out:
pythoncom.PumpWaitingMessages ()
else:
print warning_log'

def watch_for(self, raw_wql=None, notification_type='operation', wmi_class=None, delay_secs=1, fields=[], **where_clause):

    if isinstance(wmi_class, _wmi_class):
        class_name = wmi_class._class_name
    else:
        class_name = wmi_class
        wmi_class = getattr(self, class_name)
    is_extrinsic = ('__ExtrinsicEvent' in wmi_class.derivation())
    if raw_wql:
        wql = raw_wql
    else:
        fields = set((['TargetInstance'] + (fields or ['*'])))
        field_list = ',    '.join(fields)
        if is_extrinsic:
            if where_clause:
                where = ('    WHERE    ' + '    AND    '.join([("%s    =    '%s'" % (k, v)) for (k, v) in where_clause.items()]))
            else:
                where = ''
            wql = (((('SELECT    ' + field_list) + '    FROM    ') + class_name) + where)
        else:
            if where_clause:
                where = ('    AND    ' + '    AND    '.join([("TargetInstance.%s    =    '%s'" % (k, v)) for (k, v) in where_clause.items()]))
            else:
                where = ''
            wql = ("SELECT    %s    FROM    __Instance%sEvent    WITHIN    %d    WHERE    TargetInstance    ISA    '%s'    %s" % (field_list, notification_type, delay_secs, class_name, where))
    try:
        return _wmi_watcher(self._namespace.ExecNotificationQuery(wql), is_extrinsic=is_extrinsic, fields=fields)
    except pywintypes.com_error:
        handle_com_error()
