python - 编译 Python 脚本以加快加载速度
问题描述
我觉得我真的很愚蠢。我知道我可以将 .py 文件编译为 .pyc ,python -m compileall
其逻辑是脚本加载速度更快,因为它是预编译的,但如果它是主脚本,这似乎不是一个可用的功能。为了解释我的意思,假设我从命令行运行 test.py,如下所示:
python test.py
现在让我们假设 test.py 是一个大文件,它需要一些时间来转换为字节码,合乎逻辑的做法是预编译它,所以我在命令中运行以下命令:
python -m compileall test.py
然后我再次使用以下命令运行脚本:
python test.py
如果我理解正确,test.py 文件会被重新编译,基本上使预编译变得毫无意义。我弄错了吗?如果我不是,有没有办法解决这个问题?
解决方案
预编译.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 文件会被重新编译,基本上使预编译变得毫无意义。
所以这不是没有意义的。
推荐阅读
- arrays - 如何将变量从测试传递到 beforeEach 钩子?
- amazon-web-services - 云(Azure、AWS)中磁盘上的内容在重新发布给其他用户之前是否已归零?
- computer-science - 扩展名前文件名中的点(。)的目的是什么。它是某种运算符吗?
- scala - 使用 Gatling 进行慢速负载测试
- ios - UITableView - 在 Xamarin 中动画插入行
- ansible - Ansible lineinfile 在编辑前添加新行
- c# - 使用 Expression.Lambda 制作 lambda 表达式时如何使用变量
>() - java - Spring Boot ConfigurationProperties - 未映射基类
- c# - C# - 测量经过时间的最有效方法
- python - 带有 CSV 的 Jinja2 模板中的 For 循环