欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

任務(wù)管理器效果圖

完整代碼

import tkinter as tk
from tkinter import ttk
import psutil
 
# 運行此代碼前,請確保已經(jīng)安裝了 psutil 庫,可以使用 pip install psutil 進行安裝。
# 由于獲取進程信息可能會受到權(quán)限限制,某些進程的信息可能無法獲取,代碼中已經(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,))
 
    # 設(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', '進程名稱', '內(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)前所有進程。

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

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

4、 強行結(jié)束指定進程。

通過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)前所有進程。
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)]
 
 
# 獲取指定進程的所有線程
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("進程不存在")
 
 
# 強行結(jié)束指定進程
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.強行結(jié)束指定進程           *")
        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()

到此這篇關(guān)于如何使用Python實現(xiàn)一個簡單的window任務(wù)管理器的文章就介紹到這了,更多相關(guān)Python任務(wù)管理器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python?lambda?表達式形式分析

    python?lambda?表達式形式分析

    這篇文章主要介紹了python?lambda?表達式形式分析,?lambda??表達式會創(chuàng)建一個函數(shù)對象,可以對其賦值并如同普通函數(shù)一樣使用,下面通過定義了一個求平方的?lambda?表達式展開主題內(nèi)容,需要的朋友可以參考一下
    2022-04-04
  • Pytorch distributed 多卡并行載入模型操作

    Pytorch distributed 多卡并行載入模型操作

    這篇文章主要介紹了Pytorch distributed 多卡并行載入模型操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • python用win32gui遍歷窗口并設(shè)置窗口位置的方法

    python用win32gui遍歷窗口并設(shè)置窗口位置的方法

    今天小編就為大家分享一篇python用win32gui遍歷窗口并設(shè)置窗口位置的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • python中學(xué)習(xí)K-Means和圖片壓縮

    python中學(xué)習(xí)K-Means和圖片壓縮

    大家在python中會遇到關(guān)于K-Means和圖片壓縮的問題,我先通過本次文章學(xué)習(xí)一下基本原理吧。
    2017-11-11
  • Python通用驗證碼識別OCR庫ddddocr的安裝使用教程

    Python通用驗證碼識別OCR庫ddddocr的安裝使用教程

    dddd_ocr是一個用于識別驗證碼的開源庫,又名帶帶弟弟ocr,下面這篇文章主要給大家介紹了關(guān)于Python通用驗證碼識別OCR庫ddddocr的安裝使用教程,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • Python爬蟲之爬取淘女郎照片示例詳解

    Python爬蟲之爬取淘女郎照片示例詳解

    這篇文章主要介紹了Python爬蟲之爬取淘女郎照片示例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • Python導(dǎo)入不同文件夾中文件的方法詳解

    Python導(dǎo)入不同文件夾中文件的方法詳解

    在寫python程序的時候,經(jīng)常會用到引入其他文件夾里的py文件,下面這篇文章主要給大家介紹了關(guān)于Python導(dǎo)入不同文件夾中文件的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-06-06
  • Python實現(xiàn)計算信息熵的示例代碼

    Python實現(xiàn)計算信息熵的示例代碼

    信息熵(information?entropy)是信息論的基本概念。描述信息源各可能事件發(fā)生的不確定性。本文將通過Python實現(xiàn)信息熵的計算,感興趣的可以了解一下
    2022-12-12
  • 用python打印1~20的整數(shù)實例講解

    用python打印1~20的整數(shù)實例講解

    在本篇內(nèi)容中小編給大家分享了關(guān)于python打印1~20的整數(shù)的具體步驟以及實例方法,需要的朋友們參考下。
    2019-07-07
  • 讀Json文件生成pandas數(shù)據(jù)框詳情

    讀Json文件生成pandas數(shù)據(jù)框詳情

    這篇文章主要介紹了讀Json文件生成pandas數(shù)據(jù)框詳情,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下
    2022-08-08

最新評論