用Python杀掉windows平台下的进程
发布时间:2020-12-17 17:27:28 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 # "这段代码来自于一个很简单的场景:# 在python中调一个程序。给这个程序设置一个timeout# 假如一段时间程序还没有返回,就杀掉这个这个新开的进程。
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 # "这段代码来自于一个很简单的场景: # 在python中调一个程序。给这个程序设置一个timeout # 假如一段时间程序还没有返回,就杀掉这个这个新开的进程。" import ctypes import sys TH32CS_SNAPPROCESS = 0x00000002 class PROCESSENTRY32(ctypes.Structure): _fields_ = [("dwSize",ctypes.c_ulong),("cntUsage",("th32ProcessID",("th32DefaultHeapID",("th32ModuleID",("cntThreads",("th32ParentProcessID",("pcPriClassBase",("dwFlags",("szExeFile",ctypes.c_char * 260)] def getProcList(): CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot Process32First = ctypes.windll.kernel32.Process32First Process32Next = ctypes.windll.kernel32.Process32Next CloseHandle = ctypes.windll.kernel32.CloseHandle hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0) pe32 = PROCESSENTRY32() pe32.dwSize = ctypes.sizeof(PROCESSENTRY32) if Process32First(hProcessSnap,ctypes.byref(pe32)) == False: print >> sys.stderr,"Failed getting first process." return while True: yield pe32 if Process32Next(hProcessSnap,ctypes.byref(pe32)) == False: break CloseHandle(hProcessSnap) def getChildPid(pid): procList = getProcList() for proc in procList: if proc.th32ParentProcessID == pid: yield proc.th32ProcessID def killPid(pid): childList = getChildPid(pid) for childPid in childList: killPid(childPid) handle = ctypes.windll.kernel32.OpenProcess(1,False,pid) ctypes.windll.kernel32.TerminateProcess(handle,0) if __name__ =='__main__': args = sys.argv if len(args) >1 : pid = int(args[1]) killPid(pid) else: procList = getProcList() for proc in procList: print proc.szExeFile+' '+str(proc.th32ParentProcessID) + ' '+str(proc.th32ProcessID) #---------------------- # # Usage demo # #---------------------- import subprocess import time #import winproc timeout = 2 process = subprocess.Popen("cmd /k ping localhost -t",shell = True) start = int(time.time()) while process.poll()==None: now = int(time.time()) if int (now - start) >timeout: pid = process.pid break winproc.killPid(pid) print "End" 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |