Python Program execution principle

Source: Internet
Author: User

1. First view the Pycodeobject's struct in code.h

1 typedef struct {2 Pyobject_head3int co_argcount; /*#arguments, except *args * *4int co_nlocals; /*#Local Variables * /5int co_stacksize; /*#entries needed for evaluation stack * /6int co_flags; /* Co_ ..., see below */7Pyobject *co_code; /* Instruction Opcodes */8Pyobject *co_consts; /* List (constants used) */9Pyobject *co_names; /* List of strings (names used) */TenPyobject *co_varnames; /* Tuple of strings (local variable names) */ OnePyobject *co_freevars; /* Tuple of strings (free variable names) */ APyobject *co_cellvars; /* Tuple of strings (cell variable names) */ -/* The rest doesn't count for hash/cmp * / -Pyobject *co_filename; /* String (where it was loaded from) */ thePyobject *co_name; /* String (name, forReference) */ -int Co_firstlineno; /* First Source line number */ -Pyobject *co_lnotab; /* String (encoding addr<->Lineno Mapping) See -Objects/lnotab_notes.txt forDetails. */ +void *co_zombieframe; /* forOptimization only (see FRAMEOBJECT.C) */ -Pyobject *co_weakreflist; /* To support Weakrefs to code objects */ +} Pycodeobject;
View Code

2. When the module is loaded, the corresponding Pycodeobject object of the module is written. PYc, of course, in the normal process of running the code, do not see the. pyc file,

This process must be python in the library function compile, specific format such as:compile (source, filename, model[, flags[, Dont_inherit])

which

Source is a string or an AST (abstract Sytnax Tree) object.

FileName is a file name that can pass some recognizable values if it is not a code that is read from a file

The model is a compilation parameter with Eval,signal,exec. different objects are processed

The following parameters are optional

3. Testing

(1) Pycodeobject

File pycodeobject.py

1 # -*-codeing:utf-8-*- 2 " Hello the cruel world " 3 def func (): 4     Print s 5 func ()
View Code

Compile the code in the Python interactive shell to get the Pycodeobject object:

>>> src = open ("./code/pycodeobject.py"). Read ()>>> CO = compile (SRC,"pycodeobject.py",'exec')>>>dir (CO) ['__class__','__cmp__','__delattr__','__doc__','__eq__','__format__','__ge__','__getattribute__','__gt__','__hash__','__init__','__le__','__lt__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__setattr__','__sizeof__','__str__','__subclasshook__','Co_argcount','Co_cellvars','Co_code','co_consts','Co_filename','Co_firstlineno','Co_flags','Co_freevars','Co_lnotab','Co_name','Co_names','co_nlocals','co_stacksize','Co_varnames']>>>
View Code

Pycodeobjec.py's Pycodeobject object, print can be

>>>Printco.co_argcount0>>>PrintCo.co_nlocals0>>>PrintCo.co_names ('s','func')>>>Printco.co_varnames ()>>>Printco.co_consts ('Hello the cruel world', <code object func at 02118a88, file"pycodeobject.py", Line 3>, None)>>>Printco.co_coded
View Code

Parse instruction sequence

>>>ImportDis>>>PrintDis.dis (CO)2 0 Load_const 0 ('Hello the cruel world')              3Store_name 0 (s)3 6 Load_const 1 (<code object func at 02118a88, file"pycodeobject.py", Line 3>)              9make_function 01 store_name(func)5 Load_name 1(func)18call_function 021stPop_topLoad_const 2(None)25Return_value None>>>
View Code

The first column represents the line number of the following instructions in the Py file;

The second column is the offset of the instruction in the instruction sequence Co_code;

The third column is the name of the instruction opcode, which is divided into two types with operands and no operands, and opcode is a byte integer in the instruction sequence;

The fourth column is the operand oparg, which occupies two bytes in the instruction sequence, and is basically the subscript of the co_consts or co_names;

The fifth column with parentheses is the operand description.

(3) Pyframeobject

View data structures for Pyframeobject objects in Frameobject.h

1 typedef struct _FRAME {2 Pyobject_var_head3struct _frame *f_back; /* Previous Frame,orNULL */4Pycodeobject *f_code; /* Code Segment */5Pyobject *f_builtins; /* Builtin symbol table (pydictobject) */6Pyobject *f_globals; /*GlobalSymbol table (pydictobject) */7Pyobject *f_locals; /* Local symbol table (any mapping) */8Pyobject **f_valuestack; /* points after the last local */9/* Next free slotinchF_valuestack. Frame creation sets to F_valuestack.Ten frame evaluation usually NULLs it, but a Frame that yields sets it OneTo the current stack top. */ APyobject * *F_stacktop; -Pyobject *f_trace; /* Trace function */ -  the/* If an exception isRaisedinchThis frame, the next three is used to -* Record the exception info (ifAny) originallyinchThe thread state. See -* Comments before Set_exc_info ()--it's not obvious. -* Invariant:if_type isNULL, then so is _value and_traceback. +* Desired Invariant:all three is NULL,orAll three is non-NULL. that -* One isn'T currently true, but "should is". +*/ APyobject *f_exc_type, *f_exc_value, *F_exc_traceback; at  -Pythreadstate *f_tstate; -int f_lasti; /* Last InstructionifCalled * * -/*Call Pyframe_getlinenumber () instead of reading this field -Directly. As of 2.3 F_lineno isOnly valid when tracing is -Active (i.e. when F_trace isset). at and times we use inPycode_addr2line to calculate the line from the current -Bytecode index. */ toint F_lineno; /* Current line number */ +int f_iblock; /* IndexinchF_blockstack * * -Pytryblock F_blockstack[co_maxblocks]; /* for Try  andLoop blocks */ thePyobject *f_localsplus[1]; /* Locals+stack, dynamically sized */ *} Pyframeobject;
View Code

View Stack Frames

1 deffunc ():2     ImportSYS3frame =Sys._getframe ()4     Printframe.f_locals5     Printframe.f_globals6     Printframe.f_back.f_locals7     #You can print each domain of a frame8     PrintS
View Code

This code parsing is from the Python version 2.7.

Python Program execution principle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.