Pyinstaller 的 .exe 文件立即关闭

Pyinstaller's .exe file closes immediately

我有一个工作的 python 包,它是一个 CLI 工具,我想将它转换成一个 .exe 文件以将其上传到其他包管理器,所以我使用了 Pyinstaller。使用此命令构建 .exe 文件后:

pyinstaller -c --log-level=DEBUG main.py 2> build.txt --onefile --exclude-module=pytest --add-data "src;src"

我双击了 .exe 文件,但它立即关闭了,但在那一瞬间,我看到了预期的输出,它应该是命令行界面,所以 .exe 可以工作,但不完全。

main.py

from src.Categorize_CLI.__main__ import main

if __name__ == "__main__":
    main()

.spec 文件

# -*- mode: python ; coding: utf-8 -*-


block_cipher = None


a = Analysis(
    ['main.py'],
    pathex=[],
    binaries=[],
    datas=[('src', 'src')],
    hiddenimports=[],
    hookspath=[],
    hooksconfig={},
    runtime_hooks=[],
    excludes=['pytest'],
    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='main',
    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,
)

更新

我通过将 main.exe 文件拖到打开的命令提示符,然后按 enter 使其工作,但我收到错误消息:

RuntimeError: 'package' is not installed. Try passing 'package_name' instead.
[15592] Failed to execute script 'main' due to unhandled exception!

听起来像是文件结尾的脚本 运行 快给你看。您可以通过打开您的终端(cmd/poweshell in windows)并像任何其他 CLI 工具一样 运行 运行您的程序来确认这一点。

cd path\to\exe
./exe -arguments

由于您是从一个已经打开的终端启动它,所以它不会在脚本结束时关闭。

如果这是问题你可以通过添加

来解决
input("Continue...") # wait for user

更新

正如@BokiX 所说,pyinstaller 可能会导致防病毒软件误报。尝试不同的,例如努伊克塔:

pip install Nuikta

python -m nuikta main.py

安装python 程序与传统程序

传统的程序安装程序通常是一个带有一些附加功能的精美 zip 文件,用于为它所在的相关系统设置程序(例如,更改注册表、下载附加文件)。

python 程序只是一个 python 处于“冻结”状态的脚本,因此它可以 运行 独立地 在系统上没有 python 或其依赖项。一旦你有一个 exe 它应该只是 运行 而不需要被“安装”。

使用控制台程序 控制台程序是从终端执行的程序。在现代使用中,这些很常见,因此它们可以 运行 由脚本或发现打字比使用 GUI 更快的人

运行 cmd 中的代码而不是通过单击 exe

pyinstaller exe“通常”在以下情况下关闭:1 - 代码中存在错误,2 - 代码执行完成,显示输出后关闭

此外,正如 BokiX 所述,pyinstaller exe 经常被错误地标记为恶意,因此可能会在您的防病毒软件中添加一个例外。