推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
ansheng
V2EX  ›  Python

Python 代码是如何运行的?

  •  
  •   ansheng ·
    anshengme · Oct 18, 2016 · 1823 views
    This topic created in 3671 days ago, the information mentioned may be changed or developed.

    当 Python 执行代码的时候,会启用一个 Python 解释器,将源码(.py)文件读取到内存当中,然后编译成字节码(.pyc)文件,最后交给 Python 的虚拟机逐行解释并执行其内容,然后释放内存,退出程序。

    当第二次在执行当前程序的时候,会现在当前目录下寻找有没有同名的 pyc 文件,如果找到了,则直接进行运行,否则重复上面的工作。

    pyc 文件的目的其实就是为了实现代码的重用,为什么这么说呢?因为 Python 认为只要是 import 导入过来的文件,就是可以被重用的,那么他就会将这个文件编译成 pyc 文件。

    python 会在每次载入模块之前都会先检查一下 py 文件和 pyc 文件的最后修改日期,如果不一致则重新生成一份 pyc 文件,否则就直接读取运行。

    以上是我的个人理解,不知道对不对,求解。

    R4rvZ6agNVWr56V0
    R4rvZ6agNVWr56V0
    Oct 19, 2016❤️1
    1
    主题太大了,你的意思是说:《 pyc 文件存在的意义是个啥吧》
    pyc 本质是 magic number + 编译时间(或者叫修改时间?)+ PyCodeObject 组成的特定二进制编码( PyMarshal )文件
    更正:会现在当前目录下寻找有没有同名的 pyc 文件
    补充:还找同名的动态链接库如.dll 或.so

    更正:每次载入模块之前都会先检查一下 py 文件和 pyc 文件的最后修改日期
    补充:还要检查 magic number 呢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1524 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 00:37 · PVG 08:37 · LAX 16:37 · JFK 19:37
    ♥ Do have faith in what you're doing.