当前位置: 代码网 > it编程>前端脚本>Python > 如何使用Python实现一个简单的window任务管理器

如何使用Python实现一个简单的window任务管理器

2025年03月24日 Python 我要评论
任务管理器效果图完整代码import tkinter as tkfrom tkinter import ttkimport psutil # 运行此代码前,请确保已经安装了 psutil 库,可以使用

任务管理器效果图

完整代码

import tkinter as tk
from tkinter import ttk
import psutil
 
# 运行此代码前,请确保已经安装了 psutil 库,可以使用 pip install psutil 进行安装。
# 由于获取进程信息可能会受到权限限制,某些进程的信息可能无法获取,代码中已经对可能出现的异常进行了处理。
 
def get_process_info():
    process_list = []
    for proc in psutil.process_iter(['pid', 'name', 'memory_percent']):
        try:
            pid = proc.info['pid']
            name = proc.info['name']
            mem_percent = proc.info['memory_percent']
            process_list.append((pid, name, f'{mem_percent:.2f}%'))
        except (psutil.nosuchprocess, psutil.accessdenied, psutil.zombieprocess):
            continue
    return process_list
 
 
def populate_table():
    for item in process_table.get_children():
        process_table.delete(item)
    processes = get_process_info()
    for pid, name, mem_percent in processes:
        mem_value = float(mem_percent.strip('%'))
        tag = ""
        if mem_value > 10:
            tag = "high_mem"
        elif mem_value > 5:
            tag = "medium_mem"
        process_table.insert('', 'end', values=(pid, name, mem_percent), tags=(tag,))
 
    # 设置标签样式
    process_table.tag_configure("high_mem", foreground="red")
    process_table.tag_configure("medium_mem", foreground="green")
 
 
def sort_table(column, reverse):
    data = [(process_table.set(item, column), item) for item in process_table.get_children('')]
    if column == 'pid':
        data.sort(key=lambda t: int(t[0]), reverse=reverse)
    elif column == '内存占用率':
        data.sort(key=lambda t: float(t[0].strip('%')), reverse=reverse)
    else:
        data.sort(key=lambda t: t[0], reverse=reverse)
 
    for index, (_, item) in enumerate(data):
        process_table.move(item, '', index)
 
    process_table.heading(column, command=lambda: sort_table(column, not reverse))
 
 
root = tk.tk()
root.title("任务管理器")
root.geometry("700x500")
root.configure(bg="#f4f4f9")
 
style = ttk.style()
style.theme_use('clam')
style.configure('treeview', background="#e9e9f3", foreground="#333", fieldbackground="#e9e9f3",
                rowheight=25, font=('segoe ui', 10))
style.map('treeview', background=[('selected', '#73a6ff')])
style.configure('treeview.heading', background="#d1d1e0", foreground="#333", font=('segoe ui', 10, 'bold'))
 
columns = ('pid', '进程名称', '内存占用率')
process_table = ttk.treeview(root, columns=columns, show='headings')
for col in columns:
    process_table.heading(col, text=col, command=lambda c=col: sort_table(c, false))
    process_table.column(col, width=200, anchor='center')
process_table.pack(pady=20, padx=20, fill=tk.both, expand=true)
 
populate_table()
 
refresh_button = ttk.button(root, text="刷新", command=populate_table)
refresh_button.pack(pady=10)
 
root.mainloop()

方法扩展

python调用windows api实现任务管理器功能

任务管理器具体功能有:

1、 列出系统当前所有进程。

2、 列出隶属于该进程的所有线程。

3、 如果进程有窗口,可以显示和隐藏窗口。

4、 强行结束指定进程。

通过python调用windows api还是很实用的,能够结合python的简洁和windows api的强大,写出各种各样的脚本。

编码中的几个难点有:

调用api的具体方式是什么?

答:通过win32模块或ctypes模块。前者更简便,后者函数库更全。

不熟悉windows api怎么办?

通过api伴侣这个软件查询api所在的dll库,通过msdn查询api的详细解释等等。

完整代码如下:

import os
# import win32api
import win32gui
import win32process
from ctypes import *
 
 
# 列出系统当前所有进程。
def getprocesslist():
    os.system("tasklist")
 
 
# 结构体
class threadentry32(structure):
    _fields_ = [('dwsize', c_ulong),
                ('cntusage', c_ulong),
                ('th32threadid', c_ulong),
                ('th32ownerprocessid', c_ulong),
                ('tpbasepri', c_long),
                ('tpdeltapri', c_long),
                ('dwflags', c_ulong)]
 
 
# 获取指定进程的所有线程
def getthreadofprocess(pid):
    dll = windll.loadlibrary("kernel32.dll")
    snapshothandle = dll.createtoolhelp32snapshot(0x00000004, pid)
    struct = threadentry32()
    struct.dwsize = sizeof(threadentry32)
    flag = dll.thread32first(snapshothandle, byref(struct))
 
    while flag != 0:
        if(struct.th32ownerprocessid == int(pid)):
            print("线程id:"+str(struct.th32threadid))
        flag = dll.thread32next(snapshothandle, byref(struct))
    dll.closehandle(snapshothandle)
 
 
# enumwindows的回调函数
def callback(hwnd, windows):
    pidlist = win32process.getwindowthreadprocessid(hwnd)
    for pid in pidlist:
        windows.setdefault(pid, [])
        windows[pid].append(hwnd)
 
 
# 显示和隐藏指定进程的窗口
def changewindowstate(pid, status):
    windows = {}
    win32gui.enumwindows(callback, windows)
    try:
        hwndlist = windows[int(pid)]
        # 显示/隐藏窗口
        for hwnd in hwndlist:
            win32gui.showwindow(hwnd, int(status))
    except:
        print("进程不存在")
 
 
# 强行结束指定进程
def killprocess(pid):
    cmd = 'taskkill /pid ' + pid + ' /f'
    try:
        os.system(cmd)
    except exception as e:
        print(e)
 
 
if __name__ == "__main__":
    while(true):
        print()
        print()
        print("************************************")
        print("*                                  *")
        print("*     进程管理器                   *")
        print("*                                  *")
        print("*     1.获取所有进程               *")
        print("*     2.获取指定进程的所有线程     *")
        print("*     3.显示和隐藏指定进程的窗口   *")
        print("*     4.强行结束指定进程           *")
        print("*                                  *")
        print("************************************")
        option = input("请选择功能:")
 
        if option == "1":
            getprocesslist()
        elif option == "2":
            pid = input("请输入进程的pid:")
            getthreadofprocess(pid)
        elif option == "3":
            pid = input("请输入进程的pid:")
            status = input("隐藏输入0,显示输入1:")
            changewindowstate(pid, status)
        elif option == "4":
            pid = input("请输入进程的pid:")
            killprocess(pid)
        else:
            exit()

到此这篇关于如何使用python实现一个简单的window任务管理器的文章就介绍到这了,更多相关python任务管理器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com