Python - function cannot run on new thread
I am trying to kill a process notepad.exe
on windows using this function:
import thread, wmi, os
print 'CMD: Kill command called'
def kill():
c = wmi.WMI ()
Commands=['notepad.exe']
if Commands[0]!='All':
print 'CMD: Killing: ',Commands[0]
for process in c.Win32_Process ():
if process.Name==Commands[0]:
process.Terminate()
else:
print 'CMD: trying to kill all processes'
for process in c.Win32_Process ():
if process.executablepath!=inspect.getfile(inspect.currentframe()):
try:
process.Terminate()
except:
print 'CMD: Unable to kill: ',proc.name
kill() #Works
thread.start_new_thread( kill, () ) #Not working
It works like a charm when I call the function like this:
kill()
But when running the function on a new thread, it crashes and I have no idea why.
source to share
import thread, wmi, os
import pythoncom
print 'CMD: Kill command called'
def kill():
pythoncom.CoInitialize()
. . .
Running Windows functions in threads can be tricky because it often includes COM objects. Usage pythoncom.CoInitialize()
usually allows you to do this. Alternatively, you can take a look at the threading library . It is much easier to deal with it than the flow.
source to share
There are several issues (EDIT: the second issue has been resolved since my answer, "MikeHunter", so I'll skip that):
First, your program ends immediately after starting the thread, taking the thread with it. I guess this is not a long-term problem because it seems to be part of something bigger. To work around this, you can simulate something else while maintaining the program by simply adding a call time.sleep()
at the end of the script, say 5 seconds as the sleep length.
This will allow the program to give us a useful error, which in your case:
CMD: Kill command called
Unhandled exception in thread started by <function kill at 0x0223CF30>
Traceback (most recent call last):
File "killnotepad.py", line 4, in kill
c = wmi.WMI ()
File "C:\Python27\lib\site-packages\wmi.py", line 1293, in connect
raise x_wmi_uninitialised_thread ("WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex]")
wmi.x_wmi_uninitialised_thread: <x_wmi: WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom.CoInitialize[Ex] (no underlying exception)>
As you can see, this shows the real problem and leads us to the solution posted by MikeHunter.
source to share