为什么Python仅在导入脚本时保存字节码? [英] Why does Python only save the bytecode for a script if it is imported?

查看:97
本文介绍了为什么Python仅在导入脚本时保存字节码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于执行Python字节码将比运行原始源代码更快,因为Python不必重新编译,为什么Python仅在导入脚本时保存已编译的字节码?为每个执行的脚本保存.pyc文件不是更好吗?

Given that executing Python bytecode will be faster than running the original source code because Python does not have to recompile, why does Python only save the compiled bytecode when a script is imported? Wouldn't it be better to save the .pyc file for every script that's executed?

推荐答案

Python解释器的启动时间总会花费时间(即使您可能不会注意到那么多),所以它根本没有关系,而且更多与始终手动编译和执行脚本相比,启动您可能已更新的脚本更为方便.

The startup time of your Python interpreter takes time anyway (even if you might not notice it that much), so it simply doesn't matter and it is more convenient to start a script that might have been updated by you, than always compiling and executing the script manually.

比运行原始源代码要快

be faster than running the original source code

顺便说一句,Python不会运行"源代码.来自主脚本的初始源也会被编译和执行.

Btw, Python does not 'run' the source. The initial source from the main script is compiled and executed as well.

还请记住( Python简介):

从".pyc"或".pyo"文件比从".py"文件中读取文件时要好;唯一的事情".pyc"或".pyo"文件的速度更快它们已加载.

A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.

他们还说:

通过在命令行中输入脚本名称来运行脚本时,脚本的字节码永远不会写入".pyc"或".pyo"文件.因此,可以通过移动大多数脚本来减少脚本的启动时间.它的代码到模块中,并具有一个小的引导脚本,该脚本会导入该模块.也可以命名".pyc"或".pyo"文件直接在命令行上.

When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

这篇关于为什么Python仅在导入脚本时保存字节码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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