python解释器初探

本文探讨了Python解释器的工作原理,包括字节码、帧对象、跟踪回溯以及.pyc和.pyo文件的生成和使用。详细解析了Python如何运行脚本、模块和包,并详细介绍了全局解释器锁(GIL)及其影响。同时,文章还提到了Python选项和环境变量,如PYTHONPATH,以及PEP 339中关于CPython编译器的设计。
摘要由CSDN通过智能技术生成

Usages

  • run python file

    python test.py
    
  • run a module

    -m: module

    python -m pdb test.py
    python -m pydoc -p 9000
    
  • input from stdin

    (base) PS C:\> python
    Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>     
    
  • -c: source from command line

    python -c "import shutil;shutil.copytree('./tflexdb', './tflexdb.backup', ignore=lambda src,names:[name for name in names if name.endswith('.log')])"
    

    Sometime it is useful to use it in bash script if it is hard to implement with pure bash scripts.

  • run a package directory with main

    • package with __main__.py
    [willchen@fdev060101 py]$ python run_package/
    ('my_print:', 'Hello')
    [willchen@fdev060101 py]$ python xmlrpc/
    /usr/local/anaconda2/bin/python: can't find '__main__' module in 'xmlrpc/'
    
  • run pyz

    python3 -m zipapp run_package/ # generate run_package.pyz
    python3 run_package.pyz # same with run package folder
    

Input scale: stdin, cmd_line, file, module, pcakge, package.pyz

Go Over Interpreter

在这里插入图片描述

Interpreter

Byte Code: op_code + stack_index

>>> add = lambda a1 ,a2 : a1 + a2
>>> add(1,3)
4

>>> add.__code__.co_code # the bytecode as raw bytes
b'|\x00|\x01\x17\x00S\x00'
>>> list(add.__code__.co_code) # the bytecode as numbers
[124, 0, 124, 1, 23, 0, 83, 0]

>>> import dis
>>> dis.dis(add) # (line number, index of bytecode, op_name, stack index, varialbe name)
  1           0 LOAD_FAST                0 (a1)
              2 LOAD_FAST                1 (a2)
              4 BINARY_ADD
              6 RETURN_VALUE
>>>   

In C Python, there is a very long swith case code for op handle
在这里插入图片描述

Virtual Machine is a Stack Manipulator

在这里插入图片描述

Frame

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值