如何使用pyinstaller将多个python文件编译成单个.exe文件 [英] How to compile multiple python files into single .exe file using pyinstaller

查看:67
本文介绍了如何使用pyinstaller将多个python文件编译成单个.exe文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中创建了一个 GUI(使用 Tkinter),它使用 os.system('python_file.py') 从 GUI 单击一个按钮运行 python 文件.我想通过将 Tkinter 文件保留为主文件,使用 pyinstaller 将所有这些 python 文件捆绑到单个 .exe 文件中.

I have created a GUI (using Tkinter) in python and this runs python files on click of a button from GUI using os.system('python_file.py'). I wanted to bundle all these python files into single .exe file using pyinstaller by keeping the Tkinter file as main.

我通过在命令行中执行以下操作创建了 .exe 文件:

I created the .exe file by doing the following in command line:

pyinstaller --debug --onefile --noupx tkinter_app.py

pyinstaller --debug --onefile --noupx tkinter_app.py

目前我的 .spec 文件如下所示:

Currently my .spec file looks like this:

# -*- mode: python -*-

block_cipher = None

a = Analysis(['tkinter_app.py'],pathex=['C:\\test'],binaries=[],datas=[],
hiddenimports=[],hookspath=[],runtime_hooks=[],excludes=[], win_no_prefer_redirects=False,
win_private_assemblies=False, cipher=block_cipher)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='tkinter_app', debug=True, strip=False, upx=False,console=True )

我不知道如何在上面的 .spec 文件中包含其他 python 文件,以便整个应用程序正常工作.有人可以帮忙吗?

推荐答案

最好的方法是使用数组datas

例如像这样:

a = Analysis(['.\\main.py'],
             pathex=['.'],
             binaries=None,
             datas=[ ('.\\Ressources\\i18n', 'i18n'),
             ('.\\Ressources\\file1.py', '.')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

注意:确保将其放在正确的相对路径中,以便您的程序能够访问它

Note: Make sure to put it in the right relative path so your program will be able to access it

鉴于您的错误消息,问题不在于使用 PyInstaller 打包,而在于 os.system 命令.

Given your error message, the problem is not in packaging with PyInstaller but in os.system command.

os.system 相当于打开一个 DOS 命令窗口并输入你的命令 python_file.py

os.system is equivalent to opening a DOS command window and typping your command python_file.py

要访问您的 python 文件,您必须知道:

To access your python files, you have to know:

  • PyInstaller 将您打包的文件解压到一个临时文件夹中,您可以在 sys._MEIPASS 中访问该文件夹(仅适用于 .exe)
  • os.system 可用于启动 python 给定文件的完整路径,如下所示:os.system("python" + os.path.join(sys._MEIPASS, "python_file.py"))

但要小心,这只有在系统上安装了 python(并包含在 syspath 中)和 exe 时才有效.直接执行你的python文件会发送异常.

But be carefull, this will only work if python is installed on the system (and included in syspath) and from the exe. Executing directly your python file will send exception.

这篇关于如何使用pyinstaller将多个python文件编译成单个.exe文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆