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

完整代碼
import tkinter as tk
from tkinter import ttk
import psutil
# 運行此代碼前,請確保已經(jīng)安裝了 psutil 庫,可以使用 pip install psutil 進(jìn)行安裝。
# 由于獲取進(jìn)程信息可能會受到權(quán)限限制,某些進(jìn)程的信息可能無法獲取,代碼中已經(jīng)對可能出現(xiàn)的異常進(jì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,))
# 設(shè)置標(biāo)簽樣式
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("任務(wù)管理器")
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', '進(jìn)程名稱', '內(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)任務(wù)管理器功能
任務(wù)管理器具體功能有:
1、 列出系統(tǒng)當(dāng)前所有進(jìn)程。
2、 列出隸屬于該進(jìn)程的所有線程。
3、 如果進(jìn)程有窗口,可以顯示和隱藏窗口。
4、 強行結(jié)束指定進(jìn)程。
通過Python調(diào)用Windows API還是很實用的,能夠結(jié)合Python的簡潔和Windows API的強大,寫出各種各樣的腳本。
編碼中的幾個難點有:
調(diào)用API的具體方式是什么?
答:通過win32模塊或ctypes模塊。前者更簡便,后者函數(shù)庫更全。
不熟悉Windows API怎么辦?
通過API伴侶這個軟件查詢API所在的DLL庫,通過MSDN查詢API的詳細(xì)解釋等等。
完整代碼如下:
import os
# import win32api
import win32gui
import win32process
from ctypes import *
# 列出系統(tǒng)當(dāng)前所有進(jìn)程。
def getProcessList():
os.system("tasklist")
# 結(jié)構(gòu)體
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)]
# 獲取指定進(jìn)程的所有線程
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)
# 顯示和隱藏指定進(jìn)程的窗口
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("進(jìn)程不存在")
# 強行結(jié)束指定進(jìn)程
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("* 進(jìn)程管理器 *")
print("* *")
print("* 1.獲取所有進(jìn)程 *")
print("* 2.獲取指定進(jìn)程的所有線程 *")
print("* 3.顯示和隱藏指定進(jìn)程的窗口 *")
print("* 4.強行結(jié)束指定進(jìn)程 *")
print("* *")
print("************************************")
option = input("請選擇功能:")
if option == "1":
getProcessList()
elif option == "2":
pid = input("請輸入進(jìn)程的pid:")
getThreadOfProcess(pid)
elif option == "3":
pid = input("請輸入進(jìn)程的pid:")
status = input("隱藏輸入0,顯示輸入1:")
changeWindowState(pid, status)
elif option == "4":
pid = input("請輸入進(jìn)程的pid:")
killProcess(pid)
else:
exit()到此這篇關(guān)于如何使用Python實現(xiàn)一個簡單的window任務(wù)管理器的文章就介紹到這了,更多相關(guān)Python任務(wù)管理器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pytorch distributed 多卡并行載入模型操作
這篇文章主要介紹了Pytorch distributed 多卡并行載入模型操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
python用win32gui遍歷窗口并設(shè)置窗口位置的方法
今天小編就為大家分享一篇python用win32gui遍歷窗口并設(shè)置窗口位置的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
python中學(xué)習(xí)K-Means和圖片壓縮
大家在python中會遇到關(guān)于K-Means和圖片壓縮的問題,我先通過本次文章學(xué)習(xí)一下基本原理吧。2017-11-11
Python通用驗證碼識別OCR庫ddddocr的安裝使用教程
dddd_ocr是一個用于識別驗證碼的開源庫,又名帶帶弟弟ocr,下面這篇文章主要給大家介紹了關(guān)于Python通用驗證碼識別OCR庫ddddocr的安裝使用教程,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07

