最近更新于 2025-05-04 21:49
测试环境
- Windows 11 24H2
- Python 3.13.1
- Nuitka 2.7.0
- Nuitka 2.6.9
方案
判断运行时是打包还是代码状态
- 打包状态下,sys.argv[0] 为可执行文件的路径,扩展名是 .exe
- 代码状态下,sys.argv[0] 为代码文件的路径,扩展名是 .py
根据这个特点可以进行判断,下面的变量 isPackaged 值为 True 代表是 Nuitka 打包的状态,False 为代码状态
import sys
isPackaged: bool = not sys.argv[0].endswith('.py')
获取资源文件路径
一般会把用到的资源文件放在程序文件的同目录或往下的子目录中,在代码状态下就很简单,取代码文件所在目录即可。
Nuitka 用 –include-data-file= 打包的资源文件就在下面的 runtimeDir 下
import os
runtimeDir = os.path.dirname(__file__)
示例 – 代码直接执行
比如下面举一个例子
test.py
import os
import tkinter
runtimeDir = os.path.dirname(__file__)
root = tkinter.Tk()
root.iconbitmap(os.path.join(runtimeDir, 'icon.ico'))
root.mainloop()
代码文件同目录下有一个图标文件 icon.ico,直接用 Python 解释器执行,正常运行,窗口图标使用的 icon.ico
示例 – Nuitka 打包为单文件
然后用下面命令打包为单文件
nuitka --standalone --onefile --remove-output --enable-plugin=tk-inter --windows-icon-from-ico=.\icon.ico --include-data-file=.\icon.ico=.\ --output-dir=dist --output-filename=test .\test.py
可以正常执行,窗口图标正常显示
示例 – Nuitka 打包为多文件
用下面命令打包为多文件
nuitka --standalone --remove-output --enable-plugin=tk-inter --windows-icon-from-ico=.\icon.ico --include-data-file=.\icon.ico=.\ --output-dir=dist --output-filename=test .\test.py
可以正常执行,窗口图标正常显示
生成当前自身的执行命令
import sys
import os
isPackaged: bool = not sys.argv[0].endswith('.py')
if isPackaged:
exePath = sys.argv[0]
else:
exePath = f'{sys.executable} {os.path.abspath(sys.argv[0])}'
print(f'当前的执行命令为:{exePath}')
Python 解释器直接执行
Nuitka 打包为多文件
Nuitka 打包为单文件
Windows 下 Nuitka 是否打包状态判断及路径获取