[Tutor] How to kill an app from python on windows? (Tim Golden)

Tim Golden Tim.Golden at viacom-outdoor.co.uk
Wed Dec 6 10:38:59 CET 2006


[Tim Golden]
| > This link may get you started:
| >
| > http://effbot.org/pyfaq/how-do-i-emulate-os-kill-in-windows.htm
| >
| > although it may not apply, depending on the exact
| > circumstances of what you're doing.

[Paulino]
| Thank you Tim,
| 
| How do i get the pid of the process?

I'm going to cheat slightly, because I'm fairly sure
this is a sticky area, by going back to your original
requirement. I think that what you want to do is:

1) Use a document name to start the appropriate 
   viewer/app (without knowing what that app is)

2) Close that app at will so the file can be updated.

The problem is that while os.startfile will satisfy (1),
it returns no useful information about the process it
started. And that's because the underlying win32api,
ShellExecute, doesn't return anything useful. This is
specifically stated in the MS documentation.

What you can do, though, is to determine the correct
executable, setup a new process under your control,
and then terminate it when you want. This assume you
have the pywin32 extensions available. In the example
below, I'm using an .html file to demonstrate the point,
because I can generate one so the code works for both
of us. Obviously, it should work for any recognised
document type, including .pdf.

<code - loosely tested>
import os, sys
import win32api
import win32process
import win32event

filename = os.path.abspath ("temp.html")
open (filename, "w").write ("<html><body><p>Hello,
world!</p></body></html>")

hInstance, exe_filename = win32api.FindExecutable (filename)
print exe_filename, filename

hProcess, hThread, pid, tid = win32process.CreateProcess (
  None,
  '"%s" "%s2' % (exe_filename, filename),
  None, # process attributes
  None, # process attributes
  0, # inherit handles
  0, # creation flags
  None, # new environment
  None, # current directory
  win32process.STARTUPINFO ()
)
print pid

#
# This snippet waits until the app closes
#
win32event.WaitForSingleObject (hProcess, win32event.INFINITE)

#
# To kill the process either use the hProcess
# above, or retrieve it from the pid using:
#
hProcess = win32api.OpenProcess (1, 0, pid)

#
# and then
#
win32process.TerminateProcess (hProcess, 0)

</code>

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________


More information about the Tutor mailing list