[Tutor] working w/ processes?

Branimir Petrovic BranimirP@cpas.com
Mon Feb 17 14:23:19 2003


> -----Original Message-----
> From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu]
> Sent: February 17, 2003 10:33 AM
> To: Jmllr891@cs.com
> Cc: tutor@python.org
> Subject: Re: [Tutor] working w/ processes?
> 
> 
> 
> 
> On Sat, 15 Feb 2003 Jmllr891@cs.com wrote:
> 
> > I know that it is possible under *nix operating systems, but is it
> > possible to access and/or kill currently running processes under MS
> > Windows with Python?
> 
> Hello!  Has anyone replied to you about this yet?  I'm 
> getting the feeling
> your question is slightly specialized; you might want to ask on the
> python-win32 list for this one.

Solution for this on Windows is to use WMI. Sorry for the example
in JScript (didn't have time to fully re-tool to Python), but 
translating to Python should be a piece of cake for which unfortunatley
I will not have time, for quite some time :-(

Here it is:

/*////////////////////////////////////////////////////////////////////
    FileName:   KillProc.js

    Copy this script to dir in path (C:\, C:\Winnt or C:\Windows,...)
    From command line:
         C:\>KillProc notepad.exe

    Sript assumes:
        - WMI (WinXP, Win2K or WinNT with WMI core),
        - User running it must have administrative privileges.
*/////////////////////////////////////////////////////////////////////
var oShell = new ActiveXObject("Wscript.Shell");
var oArgs = WScript.Arguments;
var sArgsAry = new Array();
var sArgsLine = "";

//  --- Make sure there are comand line parameters:
if (oArgs.length==0) {
    sMsg = "Usage: \n\tC:\\>KillProc notepad.exe [winword.exe ...]"
    WScript.Echo(sMsg);
    WScript.Quit();
}

//  --- Collect script arguments (if any):
for (var i=0; i<oArgs.length ; i++) {
    //  Collect passed arguments
    sArgsLine += "\"" + oArgs(i) + "\" ";
    sArgsAry[sArgsAry.length] = oArgs(i)
}

//  --- Ensure that CScript.exe is the host:
if (!isCScript()) {
    var sMsg = "CScript.exe must be used to run this script.\n\n";
    sMsg += "To set CScript as the default host:\n\n";
    sMsg += "C:\\>WScript //H:CScript";
    WScript.Echo(sMsg);
    WScript.Quit();
}

// --- Kill process(es):
for (var i=0; i<sArgsAry.length ; i++) {
    WScript.Echo("Killing (if any): " + sArgsAry[i]);
    KillProcess(sArgsAry[i]);
}

function KillProcess(sProg) {
    try { var oWMI =
GetObject("winmgmts:{impersonationLevel=impersonate,(Debug)}");
    } catch(e) { return; }
    var sQuery = "select * from win32_process where name='" + sProg + "'";
    try { var oEnm = new Enumerator(oWMI.execquery(sQuery));
    } catch(e) { return; }

    for (;!oEnm.atEnd();oEnm.moveNext()) { oEnm.item().terminate(); }
}

function isCScript() { return (/cscript.exe$/i).test(WScript.FullName); }

// Branimir

P.S.

If someone would care translating this, resulting Python script would be:
	a) considerably shorter,
	b) much easier on one's eyes (yes aestetics do matter)...