SlideShare a Scribd company logo
Python 如何執行
演講經歷
● 2013/04 在 taipei.py 演講關於 pdb 的實作。
相關投影片:http://www.slideshare.
net/ya790026/recoverpdb
● 2013/05 在 pyconf.tw 演將 CPython 原始碼
解析。相關投影片:http://www.slideshare.
net/ya790026/c-python-23247730。
Python 如何被執行
1. 將程式碼編譯成 code object
2. 執行 code object 的 byte code,變數等相關
資訊放在 frame object 裡。
3. 一個 frame 對應到一個 code object
code object
● co_name gives the function name;
● co_varnames is a tuple containing the
names of the local variables (starting with
the argument names);
● co_consts is a tuple containing the literals
used by the bytecode;
frame object
● f_back is to the previous stack frame
(towards the caller), or None if this is the
bottom stack frame;
● f_code is the code object being executed in
this frame;
● f_locals is the dictionary used to look up
local variables;
● f_globals is used for global variables;
Stack

TOS3 TOS4 TOS1 TOS
BUTTON

TOP
op code
● opcode 定義在 Include/opcode.h
● opcode 的長度為一個 byte
● opcode 依照參數種類可分為三種
○ 無參數,如 NOP
○ 參數來源來自 stack,如BINARY_ADD
○ 參數來源來自 opcdoe 後兩個 bype,如
LOAD_CONST

● 如果一個函數使用超過 2^16 個常數?
○ 當 opcdoe 的參數來源來自opcdoe 後兩個 bype,而
該參數無法以 2 byte 來表示。則在該 opcdoe 前插入
EXTENDED_ARG。該 opcode 的參數為
(EXTENDED_ARG 的參數 <<16 | 該opcdoe 的參數)
Python Bytecode Instructions
●

●

●

NOP()
Do nothing code. Used as a placeholder
by the bytecode optimizer.
POP_TOP()
Removes the top-of-stack (TOS) item.
ROT_TWO()
Swaps the two top-most stack items.
Python Bytecode Instructions
Unary Operations take the top of the stack,
apply the operation, and push the result back
on the stack
●

●

●

UNARY_POSITIVE()
Implements TOS = +TOS.
UNARY_NEGATIVE()
Implements TOS = -TOS.
UNARY_NOT()
Implements TOS = not TOS.
Python Bytecode Instructions
Binary operations remove the top of the stack
(TOS) and the second top-most stack item
(TOS1) from the stack. They perform the
operation, and put the result back on the stack.
BINARY_POWER()
Implements TOS = TOS1 ** TOS.
BINARY_MULTIPLY()
Implements TOS = TOS1 * TOS.
Python Bytecode Instructions
Slice assignment needs even an additional
parameter. As any statement, they put nothing
on the stack.
STORE_SLICE+0()
Implements TOS[:] = TOS1.
STORE_SLICE+1()
Implements TOS1[TOS:] = TOS2.
Miscellaneous opcodes.
LOAD_FAST(var_num)
Pushes a reference to the local
co_varnames[var_num] onto the stack.
LOAD_CONST(consti)
Pushes co_consts[consti] onto the stack.
BUILD_LIST(count)
Works as BUILD_TUPLE, but creates a list.
def test(data, data1):
a=5
print 'hello',
print data
return 1
import dis
print dis.dis(test)
co_consts: (None, 5, 'hello', 1)
co_varnames: ('data', 'data1', 'a')
2
3
4

5

0 LOAD_CONST
3 STORE_FAST
6 LOAD_CONST
9 PRINT_ITEM
10 LOAD_FAST
13 PRINT_ITEM
14 PRINT_NEWLINE
15 LOAD_CONST
18 RETURN_VALUE

1 (5)
2 (a)
2 ('hello')
0 (data)

3 (1)
def test():
print 'hello',
print 'hello',
import dis
print dis.dis(test)
2

0 LOAD_CONST
3 PRINT_ITEM

1 ('hello')

3

4 LOAD_CONST
7 PRINT_ITEM
8 LOAD_CONST
11 RETURN_VALUE

1 ('hello')
0 (None)
def printf1(name, **kwargs):
print kwargs[name]
code = printf1.func_code
import dis
print dis.dis(code)
8

0 LOAD_FAST
3 LOAD_FAST
6 BINARY_SUBSCR
7 PRINT_ITEM
8 PRINT_NEWLINE
9 LOAD_CONST
12 RETURN_VALUE

1 (kwargs)
0 (name)

0 (None)
def test1():
a=1
b=2
c=a+b
d=a*b
def test2():
a, b = 1, 2
c, d = a + b, a * b
5

0 (a)

6 LOAD_CONST

2 (2)

9 STORE_FAST

1 (b)

12 LOAD_FAST

0 (a)

15 LOAD_FAST

7

1 (1)

3 STORE_FAST
6

0 LOAD_CONST

1 (b)

18 BINARY_ADD
19 STORE_FAST
8

2 (c)

22 LOAD_FAST

0 (a)

25 LOAD_FAST

1 (b)

28 BINARY_MULTIPLY
29 STORE_FAST

3 (d)

32 LOAD_CONST

0 (None)

35 RETURN_VALUE
11

0 LOAD_CONST

3 ((1, 2))

3 UNPACK_SEQUENCE

2

6 STORE_FAST
9 STORE_FAST
12

0 (a)
1 (b)

12 LOAD_FAST

0 (a)

15 LOAD_FAST

1 (b)

18 BINARY_ADD
19 LOAD_FAST

0 (a)

22 LOAD_FAST

1 (b)

25 BINARY_MULTIPLY
26 ROT_TWO
27 STORE_FAST

2 (c)

30 STORE_FAST

3 (d)

33 LOAD_CONST

0 (None)

36 RETURN_VALUE
PyEval_EvalFrameEx
● Python/ceval.c
● 負責解讀 opcdoe 並呼叫對應的動作
BINARY_ADD
1. 都是整數的話,直接相加
2. 都是字串的話,呼叫 string_concatenate
3. 不滿足上面條件,則呼叫 PyNumber_Add ( in
Object/typeobject.c)。他會去呼叫 __add__
4. 從 stack 取得兩個參數,放回一個結果
結論
1. 比較長的程式碼,op code 未必比較長
2. python 是一個程式碼大量重用的程式
Olis
● http://www.olis.com.tw
Vira: 一切渴望再度成為可能
http://viraapp.co
再看看看! -

免費簡易型防偷窺APP
謝謝大家
●
●
●
●

ya790206@gmail.com
www.blackwhite.tw
web.blackwhite.tw
blog.blackwhite.tw

More Related Content

PDF
Intro python-object-protocol
PDF
Take advantage of C++ from Python
PDF
Notes about moving from python to c++ py contw 2020
PDF
The Big Three
PPT
PPT
C++totural file
PPTX
C++ via C#
PPTX
Idiomatic C++
Intro python-object-protocol
Take advantage of C++ from Python
Notes about moving from python to c++ py contw 2020
The Big Three
C++totural file
C++ via C#
Idiomatic C++

What's hot (19)

PPTX
Mono + .NET Core = ❤️
PDF
Maintainable go
PDF
2018 cosup-delete unused python code safely - english
PDF
Start Wrap Episode 11: A New Rope
PDF
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
PDF
An Overview Of Standard C++Tr1
PDF
Demystifying Prototypes
PPTX
expression in cpp
PDF
Basic c++ 11/14 for python programmers
PPTX
#OOP_D_ITS - 2nd - C++ Getting Started
PDF
Garbage Collection
PDF
Unmanaged Parallelization via P/Invoke
PDF
Golang and Eco-System Introduction / Overview
PDF
JavaScript: enter the dragon
PPT
STL ALGORITHMS
PPTX
Boost.Python: C++ and Python Integration
PPTX
Summary of C++17 features
PDF
Про асинхронность / Максим Щепелин / Web Developer Wargaming
KEY
GoLightly: A Go Library For Building Virtual Machines
Mono + .NET Core = ❤️
Maintainable go
2018 cosup-delete unused python code safely - english
Start Wrap Episode 11: A New Rope
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
An Overview Of Standard C++Tr1
Demystifying Prototypes
expression in cpp
Basic c++ 11/14 for python programmers
#OOP_D_ITS - 2nd - C++ Getting Started
Garbage Collection
Unmanaged Parallelization via P/Invoke
Golang and Eco-System Introduction / Overview
JavaScript: enter the dragon
STL ALGORITHMS
Boost.Python: C++ and Python Integration
Summary of C++17 features
Про асинхронность / Максим Щепелин / Web Developer Wargaming
GoLightly: A Go Library For Building Virtual Machines
Ad

Similar to Python 如何執行 (20)

PDF
C++aptitude questions and answers
DOCX
Python指令英文
PDF
C++ aptitude
PPTX
Sour Pickles
PDF
Swift, swiftly
PPTX
ExSchema
PDF
Ekon 25 Python4Delphi_MX475
PDF
Python and Pytorch tutorial and walkthrough
KEY
What's New In Python 2.5
PDF
TWINS: OOP and FP - Warburton
PDF
Phil Bartie QGIS PLPython
PDF
Twins: Object Oriented Programming and Functional Programming
PDF
EKON 25 Python4Delphi_mX4
ZIP
DOCX
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
PPT
data Structure Lecture 1
PPTX
week14Pointers_II. pointers pemrograman dasar C++.pptx
PPT
Virtual Function and Polymorphism.ppt
PDF
Interfacing C++ with Python to boost your legacy apps with Python interfaces
PDF
What's new in Python 3.11
C++aptitude questions and answers
Python指令英文
C++ aptitude
Sour Pickles
Swift, swiftly
ExSchema
Ekon 25 Python4Delphi_MX475
Python and Pytorch tutorial and walkthrough
What's New In Python 2.5
TWINS: OOP and FP - Warburton
Phil Bartie QGIS PLPython
Twins: Object Oriented Programming and Functional Programming
EKON 25 Python4Delphi_mX4
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
data Structure Lecture 1
week14Pointers_II. pointers pemrograman dasar C++.pptx
Virtual Function and Polymorphism.ppt
Interfacing C++ with Python to boost your legacy apps with Python interfaces
What's new in Python 3.11
Ad

More from kao kuo-tung (16)

PDF
用 Open source 改造鍵盤
PPTX
Immutable infrastructure 介紹與實做:以 kolla 為例
PDF
Python to scala
PDF
Intorduce to Ceph
PDF
Openstack swift, how does it work?
PDF
Why is a[1] fast than a.get(1)
PPTX
減少重複的測試程式碼的一些方法
PDF
Openstack taskflow 簡介
PDF
Async: ways to store state
PDF
Openstack 簡介
PDF
Docker 原理與實作
PDF
那些年,我們一起看的例外
PDF
Python 中 += 與 join比較
PDF
Garbage collection 介紹
PDF
C python 原始碼解析 投影片
PDF
recover_pdb 原理與介紹
用 Open source 改造鍵盤
Immutable infrastructure 介紹與實做:以 kolla 為例
Python to scala
Intorduce to Ceph
Openstack swift, how does it work?
Why is a[1] fast than a.get(1)
減少重複的測試程式碼的一些方法
Openstack taskflow 簡介
Async: ways to store state
Openstack 簡介
Docker 原理與實作
那些年,我們一起看的例外
Python 中 += 與 join比較
Garbage collection 介紹
C python 原始碼解析 投影片
recover_pdb 原理與介紹

Recently uploaded (20)

PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
cuic standard and advanced reporting.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
Cloud computing and distributed systems.
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPT
Teaching material agriculture food technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
cuic standard and advanced reporting.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
“AI and Expert System Decision Support & Business Intelligence Systems”
Understanding_Digital_Forensics_Presentation.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Cloud computing and distributed systems.
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Teaching material agriculture food technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Building Integrated photovoltaic BIPV_UPV.pdf
Empathic Computing: Creating Shared Understanding
Chapter 3 Spatial Domain Image Processing.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

Python 如何執行