如何用Python实现Linux系统的应用锁定功能?
Linux下实现类似Cold Turkey Micromanager的Python方案
核心思路
模仿白名单机制,分为两个核心模块:
- 任务状态监控:实时检查目标操作(比如文档字数)是否完成
- 系统交互限制:关闭/最小化白名单以外的进程和窗口,直到任务完成
关键Python模块与工具
进程/窗口管理
psutil:跨平台进程管理库,用于枚举、终止非白名单进程wmctrl:Linux X11桌面下的窗口控制命令行工具,可通过Python调用,用于最小化非白名单窗口(Debian/Ubuntu系可通过sudo apt install wmctrl安装)xdotool:可选,用于更精细的窗口操作或模拟输入
文档监控
python-docx:读取docx格式文档的字数,适合监控Word/WPS/LibreOffice Writer保存的docx文件pyoo:可选,直接连接LibreOffice API,实时获取文档内容(需要LibreOffice开启服务)
实现步骤示例
1. 安装依赖
pip install psutil python-docx sudo apt install wmctrl # 针对Debian/Ubuntu及衍生版
2. 示例代码
import psutil import time import os import subprocess from docx import Document # 自定义配置 WHITELIST_PROCESSES = ["libreoffice-writer", "wmctrl", "python3", "gnome-shell"] # 根据桌面环境添加核心进程 TARGET_DOC = "/home/you/your_task.docx" REQUIRED_WORDS = 500 CHECK_INTERVAL = 10 # 检查间隔(秒) def count_doc_words(doc_path): """统计docx文档的单词数(按空格分割,可替换为汉字统计)""" try: doc = Document(doc_path) # 汉字统计可替换为:sum(len(paragraph.text) for paragraph in doc.paragraphs) return sum(len(paragraph.text.split()) for paragraph in doc.paragraphs) except Exception as e: print(f"读取文档失败: {e}") return 0 def clean_non_whitelist_processes(): """终止白名单以外的进程""" for proc in psutil.process_iter(['name', 'pid']): try: proc_name = proc.info['name'].lower() # 跳过自身进程和白名单进程 if proc.pid != os.getpid() and proc_name not in WHITELIST_PROCESSES: proc.terminate() time.sleep(0.5) if proc.is_running(): proc.kill() except (psutil.NoSuchProcess, psutil.AccessDenied): continue def minimize_non_whitelist_windows(): """最小化白名单以外的窗口""" result = subprocess.run(["wmctrl", "-l"], capture_output=True, text=True) if result.returncode != 0: print("wmctl调用失败,跳过窗口管理") return for line in result.stdout.splitlines(): parts = line.split(maxsplit=4) if len(parts) < 5: continue window_id, _, _, _, window_title = parts # 根据窗口标题判断是否属于白名单应用 if "LibreOffice Writer" not in window_title: subprocess.run(["wmctrl", "-i", "-r", window_id, "-b", "add,hidden"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def main(): if os.geteuid() != 0: print("错误:必须以root权限运行,否则无法终止系统进程") exit(1) print(f"开始监控,目标字数:{REQUIRED_WORDS}") while True: current_words = count_doc_words(TARGET_DOC) if current_words >= REQUIRED_WORDS: print(f"任务完成!当前字数:{current_words}") break print(f"当前进度:{current_words}/{REQUIRED_WORDS},正在限制系统交互...") clean_non_whitelist_processes() minimize_non_whitelist_windows() time.sleep(CHECK_INTERVAL) if __name__ == "__main__": main()
注意事项
- 桌面环境兼容性:
wmctrl仅支持X11桌面,Wayland环境下需要使用ydotool或对应桌面的专属API(比如GNOME的gdbus) - 文档保存提醒:
python-docx读取的是磁盘上的文件内容,需要提醒用户定期保存文档才能更新字数统计 - 白名单配置:务必添加桌面环境的核心进程(比如GNOME的
gnome-shell),避免误关闭导致桌面崩溃 - 权限控制:程序需要root权限才能终止其他用户的进程,也可通过给程序添加
CAP_KILL权限替代root运行
内容的提问来源于stack exchange,提问作者ILoveEveryone
相关产品推荐
相关产品推荐

