| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- 依赖安装器构建脚本
- Build script for dependency installer
- 功能:
- 1. 使用PyInstaller将install_dependencies.py打包成exe
- 2. 创建便携式安装包
- 3. 生成安装说明文档
- 作者: AI Assistant
- 日期: 2024
- """
- import os
- import sys
- import subprocess
- import shutil
- from pathlib import Path
- import json
- class InstallerBuilder:
- def __init__(self):
- self.script_dir = Path(__file__).parent
- self.build_dir = self.script_dir / "build"
- self.dist_dir = self.script_dir / "dist"
- self.installer_dir = self.script_dir / "installer_package"
-
- def check_pyinstaller(self):
- """检查PyInstaller是否可用"""
- try:
- import PyInstaller
- print("✓ PyInstaller 已安装")
- return True
- except ImportError:
- print("✗ PyInstaller 未安装,正在安装...")
- try:
- subprocess.run([sys.executable, '-m', 'pip', 'install', 'pyinstaller'],
- check=True)
- print("✓ PyInstaller 安装成功")
- return True
- except subprocess.CalledProcessError:
- print("✗ PyInstaller 安装失败")
- return False
-
- def create_spec_file(self):
- """创建PyInstaller规格文件"""
- spec_content = '''# -*- mode: python ; coding: utf-8 -*-
- block_cipher = None
- a = Analysis(
- ['install_dependencies.py'],
- pathex=[],
- binaries=[],
- datas=[
- ('requirements.txt', '.'),
- ],
- hiddenimports=[
- 'pkg_resources.py2_warn',
- 'packaging',
- 'packaging.version',
- 'packaging.specifiers',
- 'packaging.requirements',
- ],
- hookspath=[],
- hooksconfig={},
- runtime_hooks=[],
- excludes=[],
- win_no_prefer_redirects=False,
- win_private_assemblies=False,
- cipher=block_cipher,
- noarchive=False,
- )
- pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
- exe = EXE(
- pyz,
- a.scripts,
- a.binaries,
- a.zipfiles,
- a.datas,
- [],
- name='游戏配置工具依赖安装器',
- debug=False,
- bootloader_ignore_signals=False,
- strip=False,
- upx=True,
- upx_exclude=[],
- runtime_tmpdir=None,
- console=True,
- disable_windowed_traceback=False,
- argv_emulation=False,
- target_arch=None,
- codesign_identity=None,
- entitlements_file=None,
- icon=None,
- )
- '''
-
- spec_file = self.script_dir / "installer.spec"
- with open(spec_file, 'w', encoding='utf-8') as f:
- f.write(spec_content)
-
- print(f"✓ 规格文件已创建: {spec_file}")
- return spec_file
-
- def build_executable(self):
- """构建可执行文件"""
- spec_file = self.create_spec_file()
-
- try:
- print("开始构建可执行文件...")
- cmd = [
- sys.executable, '-m', 'PyInstaller',
- '--clean',
- '--noconfirm',
- str(spec_file)
- ]
-
- result = subprocess.run(cmd, cwd=self.script_dir, capture_output=True, text=True)
-
- if result.returncode == 0:
- print("✓ 可执行文件构建成功")
- return True
- else:
- print(f"✗ 构建失败: {result.stderr}")
- return False
-
- except Exception as e:
- print(f"✗ 构建过程中发生错误: {str(e)}")
- return False
-
- def create_installer_package(self):
- """创建安装包目录"""
- # 清理并创建安装包目录
- if self.installer_dir.exists():
- shutil.rmtree(self.installer_dir)
- self.installer_dir.mkdir()
-
- # 复制可执行文件
- exe_source = self.dist_dir / "游戏配置工具依赖安装器.exe"
- exe_dest = self.installer_dir / "游戏配置工具依赖安装器.exe"
-
- if exe_source.exists():
- shutil.copy2(exe_source, exe_dest)
- print(f"✓ 可执行文件已复制到: {exe_dest}")
- else:
- print(f"✗ 找不到可执行文件: {exe_source}")
- return False
-
- # 复制相关文件
- files_to_copy = [
- 'requirements.txt',
- '启动配置工具.bat'
- ]
-
- for file_name in files_to_copy:
- source = self.script_dir / file_name
- if source.exists():
- dest = self.installer_dir / file_name
- shutil.copy2(source, dest)
- print(f"✓ 已复制: {file_name}")
-
- return True
-
- def create_readme(self):
- """创建使用说明文档"""
- readme_content = '''# 游戏配置工具依赖安装器
- ## 简介
- 这是一个自动安装游戏配置管理工具所需Python依赖库的工具。
- ## 使用方法
- ### 方法一:使用可执行文件(推荐)
- 1. 双击运行 `游戏配置工具依赖安装器.exe`
- 2. 等待安装完成
- 3. 运行 `启动配置工具.bat` 使用配置管理工具
- ### 方法二:使用Python脚本
- 如果可执行文件无法运行,可以直接使用Python脚本:
- 1. 确保已安装Python 3.7或更高版本
- 2. 运行命令:`python install_dependencies.py`
- ## 安装的依赖库
- - **pandas**: Excel和CSV文件处理
- - **openpyxl**: Excel文件读写支持
- - **pyinstaller**: 用于打包Python脚本(可选)
- - **xlsxwriter**: 额外的Excel支持(可选)
- - **xlrd**: 旧版Excel文件支持(可选)
- ## 系统要求
- - Windows 7/8/10/11
- - Python 3.7+ (如果使用Python脚本)
- - 网络连接(用于下载依赖库)
- ## 故障排除
- ### 问题1:可执行文件无法运行
- - 确保Windows Defender或杀毒软件没有阻止程序运行
- - 尝试以管理员身份运行
- - 使用Python脚本方式安装
- ### 问题2:网络连接问题
- - 检查网络连接
- - 如果在公司网络环境,可能需要配置代理
- - 可以尝试使用手机热点
- ### 问题3:权限问题
- - 以管理员身份运行安装器
- - 确保对Python安装目录有写入权限
- ### 问题4:Python版本问题
- - 确保使用Python 3.7或更高版本
- - 可以从 https://python.org 下载最新版本
- ## 验证安装
- 安装完成后,会生成 `install_report.json` 文件,包含详细的安装信息。
- ## 联系支持
- 如果遇到问题,请检查:
- 1. `install_report.json` 文件中的错误信息
- 2. 确保网络连接正常
- 3. 确保Python环境正确配置
- ---
- 生成时间: {timestamp}
- 版本: 1.0.0
- '''
-
- from datetime import datetime
- readme_content = readme_content.format(
- timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- )
-
- readme_file = self.installer_dir / "README.md"
- with open(readme_file, 'w', encoding='utf-8') as f:
- f.write(readme_content)
-
- print(f"✓ 使用说明已创建: {readme_file}")
-
- def create_batch_installer(self):
- """创建批处理安装脚本"""
- batch_content = '''@echo off
- chcp 65001 >nul
- echo ========================================
- echo 游戏配置工具依赖自动安装器
- echo ========================================
- echo.
- echo 正在检查Python环境...
- python --version >nul 2>&1
- if errorlevel 1 (
- echo 错误: 未找到Python环境
- echo 请先安装Python 3.7或更高版本
- echo 下载地址: https://python.org
- echo.
- pause
- exit /b 1
- )
- echo Python环境检查通过
- echo.
- echo 开始安装依赖库...
- "游戏配置工具依赖安装器.exe"
- echo.
- echo 安装完成!
- echo 现在可以运行 "启动配置工具.bat" 来使用配置管理工具
- echo.
- pause
- '''
-
- batch_file = self.installer_dir / "一键安装依赖.bat"
- with open(batch_file, 'w', encoding='gbk') as f:
- f.write(batch_content)
-
- print(f"✓ 批处理安装脚本已创建: {batch_file}")
-
- def cleanup_build_files(self):
- """清理构建文件"""
- try:
- if self.build_dir.exists():
- shutil.rmtree(self.build_dir)
- print("✓ 构建临时文件已清理")
-
- # 保留dist目录,但可以选择清理
- # if self.dist_dir.exists():
- # shutil.rmtree(self.dist_dir)
-
- spec_file = self.script_dir / "installer.spec"
- if spec_file.exists():
- spec_file.unlink()
- print("✓ 规格文件已清理")
-
- except Exception as e:
- print(f"清理文件时发生错误: {str(e)}")
-
- def build_complete_installer(self):
- """构建完整的安装包"""
- print("=" * 60)
- print("游戏配置工具依赖安装器构建脚本")
- print("=" * 60)
-
- # 检查PyInstaller
- if not self.check_pyinstaller():
- return False
-
- # 构建可执行文件
- if not self.build_executable():
- return False
-
- # 创建安装包
- if not self.create_installer_package():
- return False
-
- # 创建文档
- self.create_readme()
- self.create_batch_installer()
-
- # 清理构建文件
- self.cleanup_build_files()
-
- print("\n" + "=" * 60)
- print("构建完成!")
- print(f"安装包位置: {self.installer_dir}")
- print("=" * 60)
- print("\n安装包内容:")
- for item in self.installer_dir.iterdir():
- print(f" - {item.name}")
-
- return True
- def main():
- """主函数"""
- builder = InstallerBuilder()
-
- try:
- success = builder.build_complete_installer()
-
- if success:
- print("\n构建成功!")
- print("现在可以将 'installer_package' 目录复制到其他电脑使用。")
- else:
- print("\n构建失败,请检查错误信息。")
-
- except KeyboardInterrupt:
- print("\n构建被用户中断")
- except Exception as e:
- print(f"\n构建过程中发生未预期的错误: {str(e)}")
-
- input("\n按回车键退出...")
- if __name__ == "__main__":
- main()
|