python虛擬機從編譯得到的codeobject中依次讀入每一條字節碼指令,并在當前的上下文環境中執行指令。
執行環境
這個執行環境包含了名字空間在內的等一系列動態的信息。
typedef struct _frame {
PyObject_VAR_HEAD
struct _frame *f_back; // 執行環境的上一個frame
PyCodeObject *f_code; // 對應的code object
PyObject *f_builtins; /* builtin symbol table (PyDictObject) */
PyObject *f_globals; /* global symbol table (PyDictObject) */
PyObject *f_locals; /* local symbol table (any mapping) */
PyObject **f_valuestack; // 運行時棧的棧底位置
PyObject **f_stacktop; // 運行時棧的棧頂位置
PyObject *f_trace; /* Trace function */
/* If an exception is raised in this frame, the next three are used to
* record the exception info (if any) originally in the thread state. See
* comments before set_exc_info() -- it's not obvious.
* Invariant: if _type is NULL, then so are _value and _traceback.
* Desired invariant: all three are NULL, or all three are non-NULL. That
* one isn't currently true, but "should be".
*/
PyObject *f_exc_type, *f_exc_value, *f_exc_traceback;
PyThreadState *f_tstate;
int f_lasti; // 上一條字節碼在code中的偏移位置
int f_lineno; // 當前字節碼對應的源代碼行位置
int f_iblock; /* index in f_blockstack */
PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */
PyObject *f_localsplus[1]; /* 動態內存 locals+stack */
} PyFrameObject;
動態內存
分配的f_localsplus不僅僅是運行時棧的空間,同時有局部變量的、co_freevars、co_cellvars的。使用方向也是從local_plus[0]開始,棧底在n_locals+ncells+nfrees處,然后累加。初始狀態棧頂也是指向棧底(f_valuestack = f_stacktop = n_locals+ncells+nfrees)。
獲取
在Python中可以通過sys的_getframe來獲得frame object,獲得的frame object就對應有PyFrameObject的一系列屬性。
實現自己的getframe方法
import sys
def get_current_frame():
try:
1 / 0
except Exception as e:
type, value, traceback = sys.exc_info()
return traceback.tb_frame.f_back
運行環境
運行時環境是一個全局的概念,執行環境是一個frame,是對應一個code block的概念。
在運行環境初始化后,python會調用ceval.c中的PyEval_EvalFramEx的函數。
PyEval_EvalFramEx
先初始化一些變量,取出code object和frame中的一些信息,然后就開始遍歷code object中的co_code對象來依次執行字節碼,在遍歷時會使用三個東西:
first_instr 指向字節碼開始位置
next_instr 指向下一個字節碼指令的位置
f_lasti 指向上一條已經被執行的字節碼位置
執行時有一個巨大的switch case來根據字節碼來執行相應的函數。
進程 線程
python使用的是操作系統的原生線程,有一個PyThreadState來保存關于線程的信息;對于進程,有PyInterpreterState來保存關于進程的信息。