首页 > 解决方案 > 编译 Python 脚本以加快加载速度

问题描述

我觉得我真的很愚蠢。我知道我可以将 .py 文件编译为 .pyc ,python -m compileall其逻辑是脚本加载速度更快,因为它是预编译的,但如果它是主脚本,这似乎不是一个可用的功能。为了解释我的意思,假设我从命令行运行 test.py,如下所示:

python test.py

现在让我们假设 test.py 是一个大文件,它需要一些时间来转换为字节码,合乎逻辑的做法是预编译它,所以我在命令中运行以下命令:

python -m compileall test.py

然后我再次使用以下命令运行脚本:

python test.py

如果我理解正确,test.py 文件会被重新编译,基本上使预编译变得毫无意义。我弄错了吗?如果我不是,有没有办法解决这个问题?

标签: pythonpython-3.xcompilation

解决方案


预编译.pyc./__pycache__. 通过运行以下命令,您可以获得它:

$ python3 -m compileall py.py
Compiling 'py.py'...
$ ls __pycache__
py.cpython-38.pyc
$ # It exists

为了测试运行脚本是否会重新编译所有内容,我将其删除。

$ rm -fr __pycache__
$ python3 py.py
Helloworld
$ ls __pycache__
ls: __pycache__: No such file or directory

如您所见,脚本不会被重新编译python script.py(它只是执行它。),不同于python -m compileall script.py.

如果我理解正确,test.py 文件会被重新编译,基本上使预编译变得毫无意义。

所以这不是没有意义的。


推荐阅读