[Python] 纯文本查看 复制代码
import os
import shutil, subprocess, winreg
current_dir = os.path.dirname(os.path.abspath(__file__))
install_exe = os.path.join(current_dir, "输入法本体.exe")
config_dest = os.path.join(os.environ.get("APPDATA", ""), "Rime")
help_source = os.path.join(current_dir, "Rime帮助")
# 获取桌面路径
def get_desktop_path():
try:
# 优先使用User Shell Folders,这个键存储的是用户自定义的文件夹路径
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders")
desktop_path = winreg.QueryValueEx(key, "Desktop")[0]
winreg.CloseKey(key)
# 替换环境变量占位符
desktop_path = os.path.expandvars(desktop_path)
return desktop_path
except Exception as e:
print(f"获取桌面路径失败: {str(e)}")
# 备用方案:使用USERPROFILE环境变量
return os.path.join(os.environ.get("USERPROFILE", ""), "Desktop")
# 安装输入法函数
def install_input_method():
print("\n正在安装小狼毫输入法...")
if os.path.exists(install_exe):
try:
result = subprocess.run([install_exe, "/S"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print("安装成功:", result.stdout)
return True
except subprocess.CalledProcessError as e:
print("安装失败:", e.stderr)
return False
else:
print("错误:未找到安装程序文件「输入法本体.exe」")
return False
# 安装配置文件函数
def install_config(config_choice):
if config_choice == "1":
config_source = os.path.join(current_dir, "雾凇拼音配置包", "Rime")
config_name = "雾凇拼音"
elif config_choice == "2":
config_source = os.path.join(current_dir, "白露拼音配置包", "Rime")
config_name = "白露拼音"
else:
print("无效的配置选择")
return False
print(f"\n正在安装{config_name}配置...")
print(f"配置文件源路径: {config_source}")
# 清理旧配置文件
print("\n正在清理旧配置文件...")
import time
max_attempts = 3
attempt = 0
# 多次尝试删除文件夹
while os.path.exists(config_dest) and attempt < max_attempts:
attempt += 1
try:
shutil.rmtree(config_dest, ignore_errors=True)
time.sleep(0.5)
print(f"第{attempt}次尝试删除旧配置文件夹")
except Exception as e:
print(f"第{attempt}次删除失败:{str(e)}")
time.sleep(1)
# 再次检查文件夹是否存在
if os.path.exists(config_dest):
print(f"多次尝试后仍无法删除旧配置文件夹:{config_dest}")
print("建议手动删除该文件夹后重试")
return False
print(f"旧配置文件夹「{config_dest}」已删除")
# 复制配置文件
print("\n正在复制配置文件...")
if os.path.exists(config_source):
try:
shutil.copytree(config_source, config_dest)
print("配置文件夹已成功复制到:", config_dest)
return True, config_name
except Exception as e:
print("配置文件复制失败:", str(e))
return False, ""
else:
print(f"错误:未找到{config_name}配置文件夹")
return False, ""
# 打包配置文件至桌面函数(备份用户本地配置并压缩)
def package_config_to_desktop():
print("\n正在备份并压缩用户本地配置文件至桌面...")
# 检查用户本地配置是否存在
if not os.path.exists(config_dest):
print(f"错误:未找到用户本地配置文件夹「{config_dest}」")
return False
# 创建备份zip文件名
import datetime, zipfile
now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
zip_filename = f"Rime配置备份_{now}.zip"
zip_filepath = os.path.join(desktop_path, zip_filename)
# 清理旧的同名zip文件(如果存在)
if os.path.exists(zip_filepath):
try:
os.remove(zip_filepath)
print(f"已删除旧的备份文件: {zip_filepath}")
except Exception as e:
print(f"删除旧备份文件失败:{str(e)}")
return False
# 压缩用户本地配置到zip文件
try:
with zipfile.ZipFile(zip_filepath, "w", zipfile.ZIP_DEFLATED) as zipf:
# 遍历配置目录中的所有文件和子目录
for root, dirs, files in os.walk(config_dest):
for file in files:
# 构建完整的文件路径
file_path = os.path.join(root, file)
# 构建zip文件中的相对路径
arcname = os.path.relpath(file_path, config_dest)
# 尝试添加文件到zip,如果失败则跳过
try:
zipf.write(file_path, arcname)
print(f"正在压缩: {arcname}")
except Exception as file_e:
print(f"跳过被占用的文件: {arcname} (错误: {str(file_e)})")
print(f"\n用户本地配置已成功备份并压缩至桌面: {zip_filepath}")
print(f"备份内容:{config_dest} → {zip_filepath}")
return True
except Exception as e:
print(f"备份并压缩配置文件失败:{str(e)}")
return False
# 输出帮助文件至桌面函数
def output_help_files():
print("\n正在输出帮助文件至桌面...")
# 检查帮助文件夹是否存在
if not os.path.exists(help_source):
print(f"错误:未找到帮助文件夹「{help_source}」")
return False
# 清理旧的帮助文件夹(如果存在)
if os.path.exists(help_dest):
try:
shutil.rmtree(help_dest, ignore_errors=True)
print(f"已删除旧的帮助文件夹: {help_dest}")
except Exception as e:
print(f"删除旧帮助文件夹失败:{str(e)}")
return False
# 复制帮助文件夹到桌面
try:
shutil.copytree(help_source, help_dest)
print(f"\n帮助文件已成功输出至桌面: {help_dest}")
return True
except Exception as e:
print(f"输出帮助文件失败:{str(e)}")
return False
# 获取桌面路径
desktop_path = get_desktop_path()
help_dest = os.path.join(desktop_path, "Rime帮助")
# 主循环
while True:
# 用户选择操作
print("\n请选择要执行的操作:")
print("0. 安装小狼毫输入法")
print("1. 安装雾凇拼音配置")
print("2. 安装白露拼音配置")
print("3. 输出帮助文件至桌面")
print("9. 打包本地配置文件至桌面")
print("q. 退出程序")
print("By Muou 2025-11-28")
choice = input("请输入选项 (0,1,2,3,9,q): ").strip().lower()
# 执行用户选择的操作
if choice == "0":
# 仅安装输入法
if install_input_method():
print("\n✅ 小狼毫输入法安装完成!")
else:
print("\n❌ 安装失败!")
elif choice == "1" or choice == "2":
# 安装配置文件
success, config_name = install_config(choice)
if success:
print(f"\n✅ {config_name}配置安装完成!")
else:
print("\n❌ 配置安装失败!")
elif choice == "3":
# 输出帮助文件至桌面
if output_help_files():
print("\n✅ 帮助文件输出完成!")
else:
print("\n❌ 帮助文件输出失败!")
elif choice == "9":
# 打包本地配置文件至桌面
if package_config_to_desktop():
print("\n✅ 本地配置文件打包完成!")
else:
print("\n❌ 本地配置文件打包失败!")
elif choice == "q":
# 退出程序
print("\n❌ 程序已退出!")
break
else:
print("\n❌ 无效选项!请重新输入。")
# 程序结束
exit(0)