如何在保持 .py 源代码可编辑的同时将 python 打包为 exe?

How to pack a python to exe while keeping .py source code editable?

我正在创建一个 python 脚本,它应该可以自我修改并且可以移植。

我可以单独实现这些目标中的每一个,但不能一起实现。

我使用 cx_freeze 或 pyinstaller 将我的 .py 打包为 exe,因此它是可移植的;但是后来我有很多 .pyc 编译文件,我无法从软件本身编辑我的 .py 文件。

有没有办法保持脚本的可移植性和轻量级(因此 70mb 可移植 python 环境不是一个选项)但仍然可编辑?

我们的想法是拥有一种类似 python.exe 的 exe“解释器”,但链接所有库,正如 pyinstaller 允许的那样,它运行 .py 文件,因此 .py 脚本可以自行编辑或被其他脚本编辑,仍然由解释器执行。

首先定义你的主脚本(不能更改)main_script.py。在子文件夹(例如命名为 data)中创建 patch_script.py

main_script.py:

import sys
sys.path.append('./data')
import patch_script

在子文件夹内:

data\patch_script.py:

print('This is the original file')

在根文件夹中创建一个规范文件,例如通过 运行 pyinstaller main_script.py。 在 spec 文件中,将补丁脚本添加为数据资源:

     ...
     datas=[('./data/patch_script.py', 'data' ) ],
     ...

运行pyinstaller main_sript.spec。执行exe文件,应该打印

This is the original file

将补丁脚本编辑为例如说:

print('This is the patched file')

重新运行 exe 文件,它应该打印出来

This is the patched file

注意:由于这是一个 PoC,它可以工作但容易出现安全问题,因为数据目录中的 python 文件可用于注入任意代码(您没有任何控制)。您可能需要考虑使用 PIP 等使用的适当包和更新脚本。