Python如何读取和解释源文件? [英] How does Python read and interpret source files?

查看:272
本文介绍了Python如何读取和解释源文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我运行一个Python(2.7,尽管我不确定这样做是否有帮助)脚本。我选择终止,或以某种方式切换回我的编辑环境,而不是终止脚本。然后,我可以修改脚本并将其保存,但是在仍在运行的脚本中这没有任何改变。

Say I run a Python (2.7, though I'm not sure that makes a difference here) script. Instead of terminating the script, I tab out, or somehow switch back to my editing environment. I can then modify the script and save it, but this changes nothing in the still-running script.

Python是否在启动时将所有源文件完全加载到内存中?我的印象是这是Python解释器的工作方式,但这与我对Python解释器的其他观点相矛盾:我听说 .pyc 文件用作字节码。适用于Python的虚拟机,例如Java中的 .class 文件。但是,与此同时,Python的一些(在我的理解中很少)实现也使用即时编译技术。

Does Python load all source files into memory completely at launch? I am under the impression that this is how the Python interpreter works, but this contradicts my other views of the Python interpreter: I have heard that .pyc files serve as byte-code for Python's virtual machine, like .class files in Java. At the same time however, some (very few in my understanding) implementations of Python also use just-in-time compilation techniques.

所以我认为如果我在脚本运行时对 .py 文件进行了更改,直到重新运行脚本后,我才能看到该更改,因为在启动时所有必需的 .py 文件被编译为 .pyc 文件,只需修改 .py 文件不会重新制作 .pyc 文件吗?

So am I correct in thinking that if I make a change to a .py file while my script is running, I don't see that change until I re-run the script, because at launch all necessary .py files are compiled into .pyc files, and simply modifying the .py files does not remake the .pyc files?

如果这是正确的,那为什么不这样做大型程序,例如我正在处理的约6,550千字节源代码分布在20多个 .py 文件中的程序,在启动时需要永久​​编译吗?程序本身如何快速

If that is correct, then why don't huge programs, like the one I'm working on with ~6,550 kilobytes of source code distributed over 20+ .py files, take forever to compile at startup? How is the program itself so fast?

其他信息:


  • 我没有使用第三方模块。所有文件都已本地写入。主源文件相对较小(10 kB),但是我主要处理的源文件为65 kB。

推荐答案

Python会加载主脚本进入内存,将其编译为字节码并运行。如果在此期间修改源文件,则不会影响字节码。

Python loads the main script into memory, compiles it into bytecode and runs that. If you modify the source file in the meantime, you're not affecting the bytecode.

如果您将脚本作为主要脚本运行(即像这样调用它 python myfile.py ,则脚本退出时字节码将被丢弃。

If you're running the script as the main script (i. e. by calling it like python myfile.py, then the bytecode will be discarded when the script exits.

如果要导入但是,该脚本将以 .pyc 文件的形式将字节码写入磁盘,除非再次修改相应的 .py 文件。

If you're importing the script, however, then the bytecode will be written to disk as a .pyc file which won't be recompiled when imported again, unless you modify the corresponding .py file.

您的6.5 MB大型程序包含许多模块,这些模块是由(可能很小的)主脚本导入的,因此仅所有其他文件都将准备好运行它们的 .pyc 文件。

Your big 6.5 MB program consists of many modules which are imported by the (probably small) main script, so only that will have to be compiled at each run. All the other files will have their .pyc file ready to run.

这篇关于Python如何读取和解释源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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