最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何使用Python實現(xiàn)一個簡單的window任務管理器

 更新時間:2025年03月24日 15:03:17   作者:YiWait  
這篇文章主要為大家詳細介紹了如何使用Python實現(xiàn)一個簡單的window任務管理器,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下

任務管理器效果圖

完整代碼

import tkinter as tk
from tkinter import ttk
import psutil
 
# 運行此代碼前,請確保已經(jīng)安裝了 psutil 庫,可以使用 pip install psutil 進行安裝。
# 由于獲取進程信息可能會受到權限限制,某些進程的信息可能無法獲取,代碼中已經(jīng)對可能出現(xiàn)的異常進行了處理。
 
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 == '內(nèi)存占用率':
        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', '進程名稱', '內(nèi)存占用率')
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調(diào)用Windows API實現(xiàn)任務管理器功能

任務管理器具體功能有:

1、 列出系統(tǒng)當前所有進程。

2、 列出隸屬于該進程的所有線程。

3、 如果進程有窗口,可以顯示和隱藏窗口。

4、 強行結束指定進程。

通過Python調(diào)用Windows API還是很實用的,能夠結合Python的簡潔和Windows API的強大,寫出各種各樣的腳本。

編碼中的幾個難點有:

調(diào)用API的具體方式是什么?

答:通過win32模塊或ctypes模塊。前者更簡便,后者函數(shù)庫更全。

不熟悉Windows API怎么辦?

通過API伴侶這個軟件查詢API所在的DLL庫,通過MSDN查詢API的詳細解釋等等。

完整代碼如下:

import os
# import win32api
import win32gui
import win32process
from ctypes import *
 
 
# 列出系統(tǒng)當前所有進程。
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的回調(diào)函數(shù)
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實現(xiàn)一個簡單的window任務管理器的文章就介紹到這了,更多相關Python任務管理器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • python panda庫從基礎到高級操作分析

    python panda庫從基礎到高級操作分析

    本文介紹了Pandas庫的核心功能,包括處理結構化數(shù)據(jù)的Series和DataFrame數(shù)據(jù)結構,數(shù)據(jù)讀取、清洗、分組聚合、合并、時間序列分析及大數(shù)據(jù)優(yōu)化技巧,強調(diào)其高效性、靈活性和與科學計算庫的集成能力,感興趣的朋友跟隨小編一起看看吧
    2025-08-08
  • python創(chuàng)建多個logging日志文件的方法實現(xiàn)

    python創(chuàng)建多個logging日志文件的方法實現(xiàn)

    本文主要介紹了python創(chuàng)建多個logging日志文件的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-07-07
  • PyCharm配置mongo插件的方法

    PyCharm配置mongo插件的方法

    今天小編就為大家分享一篇PyCharm配置mongo插件的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • Python填充任意顏色,不同算法時間差異分析說明

    Python填充任意顏色,不同算法時間差異分析說明

    這篇文章主要介紹了Python填充任意顏色,不同算法時間差異分析說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python中選擇排序的實現(xiàn)與優(yōu)化

    Python中選擇排序的實現(xiàn)與優(yōu)化

    選擇排序(Selection?Sort)是一種簡單但有效的排序算法,本文將詳細介紹選擇排序算法的原理和實現(xiàn),并提供相關的Python代碼示例,需要的可以參考一下
    2023-06-06
  • 一文詳解Python函數(shù)定義的12個參數(shù)傳遞技巧

    一文詳解Python函數(shù)定義的12個參數(shù)傳遞技巧

    在Python中,函數(shù)是代碼復用的核心工具,這篇文章主要為大家詳細介紹了Python函數(shù)定義的12個參數(shù)傳遞技巧,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下
    2026-02-02
  • 創(chuàng)建Python Docker鏡像的詳細步驟

    創(chuàng)建Python Docker鏡像的詳細步驟

    Python和Docker是兩個極其流行的技術,結合它們可以創(chuàng)建強大的應用程序,Docker允許將應用程序及其依賴項打包到一個獨立的容器中,而Python則提供了豐富的庫和工具來開發(fā)應用程序,本文將提供如何創(chuàng)建Python Docker鏡像的全面指南,,需要的朋友可以參考下
    2023-12-12
  • Python中使用__new__實現(xiàn)單例模式并解析

    Python中使用__new__實現(xiàn)單例模式并解析

    單例模式是一個經(jīng)典設計模式,簡要的說,一個類的單例模式就是它只能被實例化一次,實例變量在第一次實例化時就已經(jīng)固定。 這篇文章主要介紹了Python中使用__new__實現(xiàn)單例模式并解析 ,需要的朋友可以參考下
    2019-06-06
  • 使用Python實現(xiàn)異步文件讀寫功能

    使用Python實現(xiàn)異步文件讀寫功能

    在處理大規(guī)模數(shù)據(jù)或多個文件時,同步讀寫操作會導致程序阻塞,影響整體性能,通過異步文件讀寫,可以顯著提高程序的響應速度和并發(fā)處理能力,本文將詳細介紹如何使用Python實現(xiàn)異步文件讀寫,需要的朋友可以參考下
    2025-09-09
  • Python使用XlsxWriter生成Excel并自動輸出統(tǒng)計報表

    Python使用XlsxWriter生成Excel并自動輸出統(tǒng)計報表

    很多 Python 學習者在接觸辦公自動化時,都會很自然地想到一個需求:能不能用 Python 批量處理 Excel,并自動生成一份像樣的統(tǒng)計報表?這篇文章會帶你系統(tǒng)掌握 XlsxWriter 的核心用法,并通過一個完整案例,學會如何自動生成一份統(tǒng)計報表,需要的朋友可以參考下
    2026-05-05

最新評論

台安县| 河曲县| 繁昌县| 青龙| 荥阳市| 榕江县| 阿城市| 鱼台县| 达日县| 新竹市| 东乡县| 厦门市| 张家港市| 托克托县| 土默特右旗| 台南市| 德昌县| 舞阳县| 鄂尔多斯市| 江孜县| 枣庄市| 介休市| 乐山市| 隆回县| 芮城县| 闵行区| 遂宁市| 三明市| 理塘县| 奉化市| 苍山县| 威宁| 宜黄县| 吴堡县| 杭州市| 嘉黎县| 修水县| 凤山市| 汾西县| 神池县| 沧州市|