用Python杀进程的方法之windows平台示例详解,python示例,本篇Python语言源码
用Python杀进程的方法之windows平台示例详解,python示例,本篇Python语言源码
本篇Python语言源码为:如何在windows平台下如何用Python杀进程的方法。主要的思路是在Python程序设置一个timeout,条件是一定时间内,如果这个程序没有返回,那么执行“杀掉这个这个新开的进程”。这就是我大概的思路,大家也可以自由发挥用你们的方法来杀进程。
如下就是我用Python杀进程的方法(windows)源码:需要用到ctypes、sys两个方法模块
import ctypesimport sysTH32CS_SNAPPROCESS = 0x00000002class PROCESSENTRY32(ctypes.Structure): _fields_ = [("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32ProcessID", ctypes.c_ulong), ("th32DefaultHeapID", ctypes.c_ulong), ("th32ModuleID", ctypes.c_ulong), ("cntThreads", ctypes.c_ulong), ("th32ParentProcessID", ctypes.c_ulong), ("pcPriClassBase", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("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) #----------------------## www.iplaypy.com##----------------------import subprocessimport time#import winproctimeout = 2process = 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 breakwinproc.killPid(pid) print "End"
网上还有好多关于用Python语言杀进程的方法,但都不是太完整。希望我的这个源码能帮到有这方面需求的朋友们。
编橙之家文章,
相关内容
- 用Python求素数的快速算法源码示例,python素数,本篇文章
- Python select简单实现socket服务器的方法,pythonsocket,编橙
- Python MySQLdb模块简单封装的方法源码,pythonmysqldb,日常工
- Python Google talk聊天机器人源码,python聊天机器人,Pytho
- Python语言判断输入的是否是回文数的方法,,Python语言如
- Python localtime()方法计算今天是一年中第几周,pythonloc
- Python实现自动提取国家地理每日图片,,用Python urll
- Python自动输出文件夹下符合条件的全路径名,,Python自动
- Python urllib2发送即时消息到twitter的实现方法,urllib2tw
- Python 按月增加datetime月份的问题,pythondatetime,今天要为
评论关闭