pytoexe-gui 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. pytoexe/__init__.py +10 -0
  2. pytoexe/__main__.py +182 -0
  3. pytoexe/certificate.py +164 -0
  4. pytoexe/config.py +36 -0
  5. pytoexe/depscan.py +502 -0
  6. pytoexe/diagnostics.py +212 -0
  7. pytoexe/dialogs.py +128 -0
  8. pytoexe/env_manager.py +459 -0
  9. pytoexe/exeinfo.py +232 -0
  10. pytoexe/packaging.py +700 -0
  11. pytoexe/project.py +187 -0
  12. pytoexe/ui.py +465 -0
  13. pytoexe/utils.py +117 -0
  14. pytoexe/validation.py +46 -0
  15. pytoexe/web/Nunito-Light.ttf +0 -0
  16. pytoexe/web/css/general.css +175 -0
  17. pytoexe/web/css/main.css +369 -0
  18. pytoexe/web/css/modal.css +62 -0
  19. pytoexe/web/css/pytoexe.css +541 -0
  20. pytoexe/web/favicon.ico +0 -0
  21. pytoexe/web/img/chevron-square-up.svg +3 -0
  22. pytoexe/web/img/moon.svg +1 -0
  23. pytoexe/web/img/plus.svg +6 -0
  24. pytoexe/web/img/remove.svg +6 -0
  25. pytoexe/web/img/sun.svg +1 -0
  26. pytoexe/web/index.html +392 -0
  27. pytoexe/web/js/configuration.js +89 -0
  28. pytoexe/web/js/constants.js +137 -0
  29. pytoexe/web/js/environment.js +294 -0
  30. pytoexe/web/js/i18n.js +94 -0
  31. pytoexe/web/js/importExport.js +80 -0
  32. pytoexe/web/js/initialise.js +159 -0
  33. pytoexe/web/js/interface.js +365 -0
  34. pytoexe/web/js/messages.js +61 -0
  35. pytoexe/web/js/modal.js +190 -0
  36. pytoexe/web/js/packaging.js +130 -0
  37. pytoexe/web/js/properties.js +257 -0
  38. pytoexe/web/js/staticEvents.js +268 -0
  39. pytoexe/web/js/utils.js +61 -0
  40. pytoexe_gui-1.1.0.dist-info/METADATA +296 -0
  41. pytoexe_gui-1.1.0.dist-info/RECORD +45 -0
  42. pytoexe_gui-1.1.0.dist-info/WHEEL +5 -0
  43. pytoexe_gui-1.1.0.dist-info/entry_points.txt +3 -0
  44. pytoexe_gui-1.1.0.dist-info/licenses/LICENSE +24 -0
  45. pytoexe_gui-1.1.0.dist-info/top_level.txt +1 -0
pytoexe/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """pytoexe - 把 Python 脚本打包成可执行程序的图形化工具。
2
+
3
+ 本项目基于 auto-py-to-exe(MIT License, Copyright (c) 2018 Brent Vollebregt)
4
+ 进行二次开发,主要新增:内置虚拟打包环境、自动依赖检测与修复、全中文界面、
5
+ 可配置的程序属性与版权/证书签名、打包后分发与中文错误诊断。by ETC
6
+ """
7
+
8
+ __version__ = "1.1.0"
9
+ __author__ = "ETC"
10
+ __license__ = "MIT"
pytoexe/__main__.py ADDED
@@ -0,0 +1,182 @@
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import shutil
5
+ import sys
6
+ import tempfile
7
+
8
+ from . import __version__, config, utils, validation
9
+
10
+
11
+ def _run_gui(args):
12
+ from . import ui
13
+
14
+ logging.basicConfig(level=getattr(logging, args.logging_level), format="%(message)s")
15
+
16
+ config.temporary_directory = args.build_directory_override or tempfile.mkdtemp()
17
+ config.package_filename = args.filename
18
+ config.supplied_ui_configuration = args.config
19
+ config.default_output_directory = os.path.abspath(args.output_dir)
20
+ config.language_hint = "zh"
21
+
22
+ if args.no_ui:
23
+ config.ui_open_mode = config.UIOpenMode.NONE
24
+ elif args.default_browser:
25
+ config.ui_open_mode = config.UIOpenMode.DEFAULT_BROWSER
26
+ else:
27
+ config.ui_open_mode = config.UIOpenMode.CHROME_OR_EDGE
28
+
29
+ ui.start(config.ui_open_mode)
30
+
31
+ if args.build_directory_override is None:
32
+ shutil.rmtree(config.temporary_directory, ignore_errors=True)
33
+
34
+
35
+ def _run_cli(args):
36
+ """命令行打包模式,便于自动化与 CI 使用。"""
37
+ from . import packaging, project
38
+
39
+ config.temporary_directory = tempfile.mkdtemp()
40
+ source = os.path.abspath(args.filename)
41
+ if not os.path.isfile(source):
42
+ print("错误:文件不存在:{}".format(source), file=sys.stderr)
43
+ return 2
44
+
45
+ try:
46
+ project_info = project.prepare(source, os.path.join(config.temporary_directory, "projects", "cli"))
47
+ except project.ProjectError as e:
48
+ print("项目无法打包:{}".format(e), file=sys.stderr)
49
+ return 2
50
+
51
+ script = project_info["entry"]
52
+ name = args.name or project_info.get("suggestedName") or os.path.splitext(os.path.basename(script))[0]
53
+ parts = ["pyinstaller", "--noconfirm"]
54
+ parts.append("--onefile" if args.onefile else "--onedir")
55
+ parts.append("--windowed" if args.windowed else "--console")
56
+ parts += ["--name", name]
57
+ if args.icon:
58
+ parts += ["--icon", os.path.abspath(args.icon)]
59
+ parts += args.extra_args if args.extra_args else []
60
+ parts.append(script)
61
+
62
+ options = {
63
+ "project": project_info,
64
+ "outputDirectory": os.path.abspath(args.output_dir),
65
+ "increaseRecursionLimit": False,
66
+ "environment": {
67
+ "mode": "current" if args.no_venv else "venv",
68
+ "path": os.path.abspath(args.env_dir or config.DEFAULT_ENV_DIR),
69
+ "python": args.python or sys.executable,
70
+ },
71
+ "properties": {
72
+ "enabled": bool(args.product_name or args.copyright),
73
+ "productName": args.product_name or name,
74
+ "fileDescription": args.description or "",
75
+ "companyName": args.company or "",
76
+ "copyright": args.copyright or "",
77
+ "productVersion": args.version_string or "1.0.0.0",
78
+ },
79
+ "distribution": {"enabled": args.bundle, "zip": True, "sha256": True, "readme": True},
80
+ "certificate": {"enabled": bool(args.certificate), "path": args.certificate or "", "password": args.cert_password or ""},
81
+ }
82
+
83
+ result = packaging.package(
84
+ pyinstaller_command=" ".join(parts),
85
+ options=options,
86
+ on_output=lambda message: print(message, end=""),
87
+ )
88
+
89
+ if result.get("ok"):
90
+ print("\n打包成功:{}({})".format(result.get("artifact"), result.get("size")))
91
+ print("日志:{}".format(result.get("logFile")))
92
+ if result.get("distribution", {}).get("zip"):
93
+ print("分发包:{}".format(result["distribution"]["zip"]))
94
+ return 0
95
+
96
+ error = result.get("error") or {}
97
+ print("\n打包失败:{}".format(error.get("title", "")))
98
+ print(error.get("summary", ""))
99
+ for issue in error.get("issues", []):
100
+ print("- {}:{}".format(issue.get("title"), issue.get("suggestion")))
101
+ if error.get("location"):
102
+ location = error["location"]
103
+ position = location.get("file") or ""
104
+ if location.get("line"):
105
+ position += " 第 {} 行".format(location["line"])
106
+ if location.get("function"):
107
+ position += "({})".format(location["function"])
108
+ print("出错位置:{}".format(position))
109
+ print("完整日志:{}".format(result.get("logFile")))
110
+ return 1
111
+
112
+
113
+ def _run_doctor():
114
+ """环境自检。"""
115
+ import platform
116
+
117
+ from . import depscan, env_manager
118
+
119
+ print("pytoexe {} (by ETC)".format(__version__))
120
+ print("Python:{} ({})".format(sys.version.split()[0], sys.executable))
121
+ print("系统:{} {}".format(platform.system(), platform.release()))
122
+ print("默认虚拟环境:{}({})".format(config.DEFAULT_ENV_DIR, "已存在" if env_manager.env_exists(config.DEFAULT_ENV_DIR) else "未创建"))
123
+ status = env_manager.status(config.DEFAULT_ENV_DIR)
124
+ if status["exists"]:
125
+ print(" 环境 Python:{} / PyInstaller:{} / 包数量:{} / 体积:{}".format(
126
+ status["pythonVersion"], status["pyinstaller"] or "未安装", status["packages"], status["size"]
127
+ ))
128
+ print("可用解释器:")
129
+ for interpreter in depscan.list_interpreters():
130
+ print(" - {}".format(interpreter["label"]))
131
+ return 0
132
+
133
+
134
+ def run():
135
+ utils.ensure_console_encoding()
136
+ parser = argparse.ArgumentParser(prog="pytoexe", description="把 Python 脚本打包成可执行程序(by ETC)")
137
+ parser.add_argument("filename", nargs="?", type=validation.argparse_file_exists, default=None, help="要打包的 Python 脚本")
138
+ parser.add_argument("-db", "--default-browser", action="store_true", help="使用系统默认浏览器打开界面")
139
+ parser.add_argument("-nu", "--no-ui", action="store_true", help="不打开浏览器,仅启动本地服务")
140
+ parser.add_argument("-c", "--config", type=validation.argparse_file_json, default=None, help="用 JSON 配置预填界面")
141
+ parser.add_argument("-o", "--output-dir", default="output", help="输出目录(默认 output)")
142
+ parser.add_argument("-bdo", "--build-directory-override", default=None, help="构建临时目录")
143
+ parser.add_argument("--logging-level", default="ERROR", choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"])
144
+ parser.add_argument("-v", "--version", action="version", version="pytoexe {}".format(__version__))
145
+
146
+ parser.add_argument("--cli", action="store_true", help="命令行打包模式(不打开界面)")
147
+ parser.add_argument("--doctor", action="store_true", help="输出当前环境自检信息")
148
+ parser.add_argument("--onefile", action="store_true", help="命令行模式:打包成单文件")
149
+ parser.add_argument("--windowed", action="store_true", help="命令行模式:隐藏控制台窗口")
150
+ parser.add_argument("--name", default=None, help="命令行模式:程序名称")
151
+ parser.add_argument("--icon", default=None, help="命令行模式:图标文件")
152
+ parser.add_argument("--no-venv", action="store_true", help="命令行模式:不使用内置虚拟环境")
153
+ parser.add_argument("--env-dir", default=None, help="命令行模式:虚拟环境目录")
154
+ parser.add_argument("--python", default=None, help="命令行模式:创建虚拟环境所用的 Python 解释器")
155
+ parser.add_argument("--bundle", action="store_true", help="命令行模式:生成 ZIP / SHA256 / 使用说明")
156
+ parser.add_argument("--product-name", default=None, help="命令行模式:产品名称")
157
+ parser.add_argument("--description", default=None, help="命令行模式:文件描述")
158
+ parser.add_argument("--company", default=None, help="命令行模式:公司名称")
159
+ parser.add_argument("--copyright", default=None, help="命令行模式:版权信息")
160
+ parser.add_argument("--version-string", default=None, help="命令行模式:产品版本,如 1.0.0.0")
161
+ parser.add_argument("--certificate", default=None, help="命令行模式:代码签名证书(.pfx/.p12)")
162
+ parser.add_argument("--cert-password", default=None, help="命令行模式:证书密码")
163
+ parser.add_argument("--extra-args", nargs=argparse.REMAINDER, default=[], help="命令行模式:追加给 PyInstaller 的参数")
164
+
165
+ args = parser.parse_args()
166
+
167
+ if args.doctor:
168
+ sys.exit(_run_doctor())
169
+
170
+ if args.cli:
171
+ if not args.filename:
172
+ parser.error("命令行打包模式必须提供脚本路径:pytoexe --cli 你的脚本.py")
173
+ sys.exit(_run_cli(args))
174
+
175
+ if (args.build_directory_override is not None) and (not os.path.isdir(args.build_directory_override)):
176
+ parser.error("--build-directory-override 必须是已存在的目录")
177
+
178
+ _run_gui(args)
179
+
180
+
181
+ if __name__ == "__main__":
182
+ run()
pytoexe/certificate.py ADDED
@@ -0,0 +1,164 @@
1
+ """代码签名证书校验:只接受真实的 .pfx / .p12 文件,并尽量解析出证书信息。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import os
7
+ from typing import Dict, Optional
8
+
9
+ ALLOWED_SUFFIXES = (".pfx", ".p12")
10
+
11
+
12
+ class CertificateError(RuntimeError):
13
+ """证书文件不合法。"""
14
+
15
+
16
+ def _read_head(path: str) -> bytes:
17
+ with open(path, "rb") as f:
18
+ return f.read(16)
19
+
20
+
21
+ def describe(path: str, password: Optional[str] = None, strict: bool = False) -> Dict[str, object]:
22
+ """检查证书文件。
23
+
24
+ strict=True 时(真正打包前)要求能被解析;strict=False 时(界面即时提示)
25
+ 只做格式和文件头校验,避免没有安装 cryptography 时误报。
26
+ """
27
+ result: Dict[str, object] = {
28
+ "ok": False,
29
+ "path": os.path.abspath(path or ""),
30
+ "message": "",
31
+ "commonName": "",
32
+ "issuer": "",
33
+ "notBefore": "",
34
+ "notAfter": "",
35
+ "expired": False,
36
+ "parsed": False,
37
+ }
38
+
39
+ if not path:
40
+ result["message"] = "还没有选择证书文件。代码签名必须提供 .pfx 或 .p12 证书。"
41
+ return result
42
+
43
+ if not os.path.isfile(path):
44
+ result["message"] = "证书文件不存在:{}".format(path)
45
+ return result
46
+
47
+ if not path.lower().endswith(ALLOWED_SUFFIXES):
48
+ result["message"] = "证书格式不正确:只支持 .pfx / .p12,当前是 {}".format(os.path.splitext(path)[1] or "未知格式")
49
+ return result
50
+
51
+ try:
52
+ size = os.path.getsize(path)
53
+ except OSError as e:
54
+ result["message"] = "无法读取证书文件:{}".format(e)
55
+ return result
56
+ if size <= 0:
57
+ result["message"] = "证书文件是空的(0 字节),请重新导出证书。"
58
+ return result
59
+ if size > 50 * 1024 * 1024:
60
+ result["message"] = "证书文件过大({}),正常证书一般不超过几十 KB,请确认文件是否正确。".format(size)
61
+ return result
62
+
63
+ head = _read_head(path)
64
+ if not head.startswith(b"\x30"):
65
+ result["message"] = "文件内容不是 PKCS#12 证书(文件头不匹配),请导出为 .pfx / .p12 后再上传。"
66
+ return result
67
+
68
+ parsed = _parse_pkcs12(path, password or "")
69
+ if parsed is not None:
70
+ result.update(parsed)
71
+ result["ok"] = True
72
+ result["parsed"] = True
73
+ if parsed.get("expired"):
74
+ result["ok"] = False
75
+ result["message"] = "证书已过期(有效期至 {}),请更换有效证书。".format(parsed.get("notAfter", ""))
76
+ else:
77
+ result["message"] = "证书有效:{}(有效期至 {})".format(
78
+ parsed.get("commonName") or "未命名证书", parsed.get("notAfter") or "未知"
79
+ )
80
+ return result
81
+
82
+ if strict or _crypto_available():
83
+ result["message"] = (
84
+ "无法解析该 .pfx/.p12 证书:证书密码错误,或文件已损坏。\n"
85
+ "请确认密码正确,或在导出证书时选择包含私钥的 PKCS#12 格式。"
86
+ )
87
+ return result
88
+
89
+ # 没有 cryptography 时只能做格式校验,打包前会再严格校验一次
90
+ result["ok"] = True
91
+ result["message"] = "证书格式正确(安装 cryptography 后可显示证书详情)。"
92
+ return result
93
+
94
+
95
+ def _crypto_available() -> bool:
96
+ try:
97
+ import cryptography # noqa: F401
98
+
99
+ return True
100
+ except Exception:
101
+ return False
102
+
103
+
104
+ def _parse_pkcs12(path: str, password: str) -> Optional[Dict[str, object]]:
105
+ try:
106
+ from cryptography.hazmat.primitives.serialization import pkcs12
107
+ except Exception:
108
+ return None
109
+
110
+ try:
111
+ with open(path, "rb") as f:
112
+ data = f.read()
113
+ key, cert, extra = pkcs12.load_key_and_certificates(data, password.encode("utf-8") or None)
114
+ except Exception:
115
+ return None
116
+
117
+ if cert is None and not extra:
118
+ return None
119
+
120
+ certificate = cert or (extra[0] if extra else None)
121
+ if certificate is None:
122
+ return None
123
+
124
+ not_before = getattr(certificate, "not_valid_before_utc", None) or getattr(certificate, "not_valid_before")
125
+ not_after = getattr(certificate, "not_valid_after_utc", None) or getattr(certificate, "not_valid_after")
126
+
127
+ if isinstance(not_before, datetime.datetime):
128
+ not_before_text = not_before.strftime("%Y-%m-%d")
129
+ else:
130
+ not_before_text = str(not_before)
131
+ if isinstance(not_after, datetime.datetime):
132
+ not_after_text = not_after.strftime("%Y-%m-%d")
133
+ expired = not_after < datetime.datetime.now(not_after.tzinfo) if not_after.tzinfo else not_after < datetime.datetime.now()
134
+ else:
135
+ not_after_text = str(not_after)
136
+ expired = False
137
+
138
+ attributes = {}
139
+ for attr in certificate.subject:
140
+ attributes[attr.oid._name] = attr.value
141
+
142
+ return {
143
+ "commonName": attributes.get("commonName", ""),
144
+ "issuer": certificate.issuer.rfc4514_string() if hasattr(certificate.issuer, "rfc4514_string") else "",
145
+ "notBefore": not_before_text,
146
+ "notAfter": not_after_text,
147
+ "expired": expired,
148
+ "hasPrivateKey": key is not None,
149
+ }
150
+
151
+
152
+ def validate(path: str, password: str = "") -> Dict[str, object]:
153
+ """打包前严格校验证书。"""
154
+ return describe(path, password, strict=True)
155
+
156
+
157
+ def prepare_for_signing(path: str, password: str = "") -> Dict[str, object]:
158
+ """校验通过后返回签名所需参数;不通过时抛 CertificateError。"""
159
+ info = validate(path, password)
160
+ if not info.get("ok"):
161
+ raise CertificateError(str(info.get("message")))
162
+ if not info.get("hasPrivateKey"):
163
+ raise CertificateError("证书里没有私钥,无法签名。请导出包含私钥的 .pfx/.p12 后重试。")
164
+ return info
pytoexe/config.py ADDED
@@ -0,0 +1,36 @@
1
+ import os
2
+ import sys
3
+
4
+ APP_NAME = "pytoexe"
5
+ APP_TITLE = "pytoexe"
6
+ APP_AUTHOR = "ETC"
7
+ APP_WEBSITE = "https://github.com/ETQWFD/pytoexe"
8
+
9
+
10
+ class UIOpenMode:
11
+ NONE = 0
12
+ CHROME_OR_EDGE = 1
13
+ DEFAULT_BROWSER = 2
14
+
15
+
16
+ # Temporary directory for packaging scripts to speed up consecutive builds. Created on application start.
17
+ temporary_directory = None
18
+
19
+ # Frontend
20
+ FRONTEND_ASSET_FOLDER = os.path.join(os.path.dirname(os.path.realpath(__file__)), "web")
21
+
22
+ # Pre-defined variables by Python
23
+ DEFAULT_RECURSION_LIMIT = sys.getrecursionlimit()
24
+
25
+ # The virtual environment used by default for packaging
26
+ DEFAULT_ENV_DIR = os.path.join(os.path.expanduser("~"), ".pytoexe", "venv")
27
+
28
+ # Where the run logs are kept
29
+ LOG_DIR = os.path.join(os.path.expanduser("~"), ".pytoexe", "logs")
30
+
31
+ # Argument-influenced configuration
32
+ package_filename = None
33
+ ui_open_mode = UIOpenMode.CHROME_OR_EDGE
34
+ supplied_ui_configuration = None
35
+ default_output_directory = os.path.abspath("output")
36
+ language_hint = "zh"