如何修改Python多进程任务的进程名称与图标?
解决Windows任务管理器中Python多进程的名称和图标显示问题
你通过multiprocessing.Process设置的name只是Python内部用来标识进程的属性,不会同步到Windows任务管理器的显示名称。下面分别给出修改进程名称和图标的可行方案:
修改进程显示名称
方案1:使用第三方库setproctitle
这个库专门用于跨平台修改进程标题,Windows下可用:
- 安装库:
pip install setproctitle
- 在子进程的任务函数开头添加修改代码:
import setproctitle def task(): # 修改任务管理器中的进程显示名称 setproctitle.setproctitle("Worker") # 你的任务逻辑代码...
启动子进程后,任务管理器里就会显示"Worker"而非默认的"Python"。
方案2:原生Windows API调用(无需第三方库)
通过ctypes调用Windows系统API修改进程名称,要求Windows 10 1607及以上版本:
import ctypes from ctypes import wintypes def set_process_title(title): kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) class PROCESS_INFORMATION_CLASS(ctypes.c_int): ProcessTitle = 20 # 对应Windows API的进程标题标识 kernel32.SetProcessInformation.argtypes = [ wintypes.HANDLE, PROCESS_INFORMATION_CLASS, wintypes.LPCVOID, wintypes.DWORD ] kernel32.SetProcessInformation.restype = wintypes.BOOL # 转换标题为Windows要求的UTF-16LE编码 title_bytes = title.encode('utf-16le') + b'\x00\x00' success = kernel32.SetProcessInformation( ctypes.windll.kernel32.GetCurrentProcess(), PROCESS_INFORMATION_CLASS.ProcessTitle, title_bytes, len(title_bytes) ) if not success: raise ctypes.WinError(ctypes.get_last_error()) def task(): set_process_title("Worker") # 你的任务逻辑代码...
修改进程图标
Windows任务管理器显示的进程图标默认是python.exe/pythonw.exe的图标,直接通过multiprocessing无法修改,可通过以下方式解决:
方案1:将脚本打包为EXE文件
使用PyInstaller打包成独立EXE并指定图标,是最通用的解决方案:
- 安装PyInstaller:
pip install pyinstaller
- 执行打包命令(替换为你的脚本名和图标路径):
pyinstaller --onefile --icon=your_icon.ico your_script.py
打包后的EXE运行时,子进程会自动使用该EXE的图标,任务管理器中会显示自定义图标。
方案2:修改GUI进程窗口图标(仅适用于带窗口的进程)
如果子进程是GUI程序,可通过修改窗口图标改变任务管理器中的显示(纯控制台进程无效):
import ctypes from ctypes import wintypes def set_window_icon(): user32 = ctypes.WinDLL('user32', use_last_error=True) # 加载自定义图标文件(替换为你的图标路径) hicon = user32.LoadImageW( None, r"C:\your_path\icon.ico", 1, # 标识加载的是图标文件 0, 0, 0x00000010 # 从文件加载的标识 ) if not hicon: raise ctypes.WinError(ctypes.get_last_error()) # 获取当前窗口句柄(GUI程序需替换为对应窗口的句柄) hwnd = user32.GetConsoleWindow() # 发送设置图标的消息 user32.SendMessageW(hwnd, 0x0080, 0, hicon) user32.SendMessageW(hwnd, 0x0080, 1, hicon) def task(): set_window_icon() # 你的GUI任务逻辑代码...
内容的提问来源于stack exchange,提问作者FuchsBene
相关产品推荐
相关产品推荐

