如何使用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創(chuàng)建多個logging日志文件的方法實現(xiàn)
本文主要介紹了python創(chuàng)建多個logging日志文件的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07
一文詳解Python函數(shù)定義的12個參數(shù)傳遞技巧
在Python中,函數(shù)是代碼復用的核心工具,這篇文章主要為大家詳細介紹了Python函數(shù)定義的12個參數(shù)傳遞技巧,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下2026-02-02
創(chuàng)建Python Docker鏡像的詳細步驟
Python和Docker是兩個極其流行的技術,結合它們可以創(chuàng)建強大的應用程序,Docker允許將應用程序及其依賴項打包到一個獨立的容器中,而Python則提供了豐富的庫和工具來開發(fā)應用程序,本文將提供如何創(chuàng)建Python Docker鏡像的全面指南,,需要的朋友可以參考下2023-12-12
Python中使用__new__實現(xiàn)單例模式并解析
單例模式是一個經(jīng)典設計模式,簡要的說,一個類的單例模式就是它只能被實例化一次,實例變量在第一次實例化時就已經(jīng)固定。 這篇文章主要介紹了Python中使用__new__實現(xiàn)單例模式并解析 ,需要的朋友可以參考下2019-06-06
Python使用XlsxWriter生成Excel并自動輸出統(tǒng)計報表
很多 Python 學習者在接觸辦公自動化時,都會很自然地想到一個需求:能不能用 Python 批量處理 Excel,并自動生成一份像樣的統(tǒng)計報表?這篇文章會帶你系統(tǒng)掌握 XlsxWriter 的核心用法,并通過一個完整案例,學會如何自動生成一份統(tǒng)計報表,需要的朋友可以參考下2026-05-05

