from contextlib import contextmanager import subprocess @contextmanager def sudo_open(file_path, mode='r', encoding='utf-8'): """ 上下文管理器,以 sudo 权限打开文件,支持读取和写入模式。 :param file_path: 文件路径 :param mode: 打开文件的模式 ('r' 或 'w') :param encoding: 文件编码 """ try: # 检查打开模式,读取或写入 if mode == 'r': # 使用 sudo 以读取文件 result = subprocess.run(["sudo", "cat", file_path], capture_output=True, text=True, encoding=encoding) if result.returncode != 0: raise PermissionError(f"无法读取文件: {file_path}") content = result.stdout yield content elif mode == 'w': raise PermissionError(f"不允许以sudo权限写入文件: {file_path}") else: raise ValueError("只支持 'r' 或 'w' 模式") except Exception as e: raise e finally: pass