34 lines
1.3 KiB
Python
34 lines
1.3 KiB
Python
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':
|
|
# 使用 sudo 打开文件并写入内容
|
|
def write_content(content):
|
|
result = subprocess.run(["sudo", "tee", file_path], input=content, text=True, capture_output=True, encoding=encoding)
|
|
if result.returncode != 0:
|
|
raise PermissionError(f"无法写入文件: {file_path}")
|
|
return result.stdout
|
|
|
|
yield write_content
|
|
else:
|
|
raise ValueError("只支持 'r' 或 'w' 模式")
|
|
except Exception as e:
|
|
raise e
|
|
finally:
|
|
pass |