Python 字節碼

2021-03-02 技術流 Py

百度上目前還搜不到 Python 字節碼全套內容,於是搭了梯子爬了下官方的教程。

我們都知道 python 是解釋性語言,但 python 還有個編譯過程,這個過程是將 python 代碼編譯成 字節碼,類似於彙編語言的一條一條指令。執行時,首先會讀取指令,底層的 C 語言代碼中寫有上千行的 switch case 語句與這個指令相匹配並執行相關代碼。

下面就是 python 字節碼大全,了解字節碼有助於我們更深入地熟悉 python 代碼的執行。

Do nothing code.  Used as a placeholder by the bytecode optimizer.

Removes the top-of-stack (TOS) item.

Swaps the two top-most stack items.

Lifts second and third stack item one position up, moves top down to positionthree.

Lifts second, third and forth stack items one position up, moves top downto position four.

Duplicates the reference on top of the stack.

Duplicates the two references on top of the stack, leaving them in thesame order.

Implements TOS = not TOS.

Implements TOS = iter(TOS).

If TOS is a generator iterator or coroutine objectit is left as is.  Otherwise, implements TOS = iter(TOS).

Implements TOS = TOS1 ** TOS.

Implements TOS = TOS1 * TOS.

Implements TOS = TOS1 @ TOS.

Implements TOS = TOS1 // TOS.

Implements TOS = TOS1 / TOS.

Implements TOS = TOS1 % TOS.

Implements TOS = TOS1 + TOS.

Implements TOS = TOS1 - TOS.

Implements TOS = TOS1[TOS].

Implements TOS = TOS1 << TOS.

Implements TOS = TOS1 >> TOS.

Implements TOS = TOS1 & TOS.

Implements TOS = TOS1 ^ TOS.

Implements TOS = TOS1 | TOS.

Implements in-place TOS = TOS1 ** TOS.

Implements in-place TOS = TOS1 * TOS.

Implements in-place TOS = TOS1 @ TOS.

Implements in-place TOS = TOS1 // TOS.

Implements in-place TOS = TOS1 / TOS.

Implements in-place TOS = TOS1 % TOS.

Implements in-place TOS = TOS1 + TOS.

Implements in-place TOS = TOS1 - TOS.

Implements in-place TOS = TOS1 << TOS.

Implements in-place TOS = TOS1 >> TOS.

Implements in-place TOS = TOS1 & TOS.

Implements in-place TOS = TOS1 ^ TOS.

Implements in-place TOS = TOS1 | TOS.

Implements TOS1[TOS] = TOS2.

Implements del TOS1[TOS].

Implements TOS = get_awaitable(TOS), where get_awaitable(o)returns o if o is a coroutine object or a generator object withthe CO_ITERABLE_COROUTINE flag, or resolveso.await.

Implements TOS = TOS.aiter().

Implements PUSH(get_awaitable(TOS.anext())).  See GET_AWAITABLEfor details about get_awaitable

Terminates an async for loop.  Handles an exception raisedwhen awaiting a next item.  If TOS is StopAsyncIteration pop 7values from the stack and restore the exception state using the secondthree of them.  Otherwise re-raise the exception using the three valuesfrom the stack.  An exception handler block is removed from the block stack.

Resolves aenter and aexit from the object on top of thestack.  Pushes aexit and result of aenter() to the stack.

Creates a new frame object.

Implements the expression statement for the interactive mode.  TOS is removedfrom the stack and printed.  In non-interactive mode, an expression statementis terminated with POP_TOP.

Calls set.add(TOS1[-i], TOS).  Used to implement set comprehensions.

Calls list.append(TOS[-i], TOS).  Used to implement list comprehensions.

Calls dict.setitem(TOS1[-i], TOS1, TOS).  Used to implement dictcomprehensions.

Returns with TOS to the caller of the function.

Pops TOS and yields it from a generator.

Pops TOS and delegates to it as a subiterator from a generator.

Checks whether annotations is defined in locals(), if not it isset up to an empty dict. This opcode is only emitted if a classor module body contains variable annotationsstatically.

Loads all symbols not starting with '_' directly from the module TOS tothe local namespace. The module is popped after loading all names. Thisopcode implements from module import *.

Removes one block from the block stack.  Per frame, there is a stack ofblocks, denoting try statements, and such.

Removes one block from the block stack. The popped block must be an exceptionhandler block, as implicitly created when entering an except handler.  Inaddition to popping extraneous values from the frame stack, the last threepopped values are used to restore the exception state.

Cleans up the value stack and the block stack.  If preserve_tos is not0 TOS first is popped from the stack and pushed on the stack afterperforming other stack operations:

Pushes NULL onto the stack for using it in END_FINALLY,POP_FINALLY, WITH_CLEANUP_START andWITH_CLEANUP_FINISH.  Starts the finally block.

Terminates a finally clause.  The interpreter recalls whether theexception has to be re-raised or execution has to be continued depending onthe value of TOS.

Pushes builtins.build_class() onto the stack.  It is later calledby CALL_FUNCTION to construct a class.

This opcode performs several operations before a with block starts.  First,it loads exit() from the context manager and pushes it ontothe stack for later use by WITH_CLEANUP_START.  Then,enter() is called, and a finally block pointing to deltais pushed.  Finally, the result of calling the enter() method is pushed ontothe stack.  The next opcode will either ignore it (POP_TOP), orstore it in (a) variable(s) (STORE_FAST, STORE_NAME, orUNPACK_SEQUENCE).

Starts cleaning up the stack when a with statement block exits.

Finishes cleaning up the stack when a with statement block exits.

Implements name = TOS. namei is the index of name in the attributeco_names of the code object. The compiler tries to useSTORE_FAST or STORE_GLOBAL if possible.

Implements del name, where namei is the index into co_namesattribute of the code object.

Unpacks TOS into count individual values, which are put onto the stackright-to-left.

Implements assignment with a starred target: Unpacks an iterable in TOS intoindividual values, where the total number of values can be smaller than thenumber of items in the iterable: one of the new values will be a list of allleftover items.

Implements TOS.name = TOS1, where namei is the index of name inco_names.

Implements del TOS.name, using namei as index into co_names.

Works as STORE_NAME, but stores the name as a global.

Works as DELETE_NAME, but deletes a global name.

Pushes co_consts[consti] onto the stack.

Pushes the value associated with co_names[namei] onto the stack.

Creates a tuple consuming count items from the stack, and pushes theresulting tuple onto the stack.

Works as BUILD_TUPLE, but creates a list.

Works as BUILD_TUPLE, but creates a set.

Pushes a new dictionary object onto the stack.  Pops 2 * count itemsso that the dictionary holds count entries:{..., TOS3: TOS2, TOS1: TOS}.

The version of BUILD_MAP specialized for constant keys. Pops thetop element on the stack which contains a tuple of keys, then starting fromTOS1, pops count values to form values in the built dictionary.

Concatenates count strings from the stack and pushes the resulting stringonto the stack.

Pops count iterables from the stack, joins them in a single tuple,and pushes the result.  Implements iterable unpacking in tupledisplays (*x, *y, *z).

BUILD_TUPLE_UNPACK_WITH_CALL

This is similar to BUILD_TUPLE_UNPACK,but is used for f(*x, *y, *z) call syntax. The stack item at positioncount + 1 should be the corresponding callable f.

This is similar to BUILD_TUPLE_UNPACK, but pushes a listinstead of tuple.  Implements iterable unpacking in listdisplays [*x, *y, *z].

This is similar to BUILD_TUPLE_UNPACK, but pushes a setinstead of tuple.  Implements iterable unpacking in setdisplays {*x, *y, *z}.

Pops count mappings from the stack, merges them into a single dictionary,and pushes the result.  Implements dictionary unpacking in dictionarydisplays {*x, **y, *z}.

BUILD_MAP_UNPACK_WITH_CALL

This is similar to BUILD_MAP_UNPACK,but is used for f(*x, **y, *z) call syntax.  The stack item atposition count + 2 should be the corresponding callable f.

Replaces TOS with getattr(TOS, co_names[namei]).

Performs a Boolean operation.  The operation name can be found incmp_op[opname].

Imports the module co_names[namei].  TOS and TOS1 are popped and providethe fromlist and level arguments of import().  The moduleobject is pushed onto the stack.  The current namespace is not affected: fora proper import statement, a subsequent STORE_FAST instructionmodifies the namespace.

Loads the attribute co_names[namei] from the module found in TOS. Theresulting object is pushed onto the stack, to be subsequently stored by aSTORE_FAST instruction.

Increments bytecode counter by delta.

If TOS is true, sets the bytecode counter to target.  TOS is popped.

If TOS is false, sets the bytecode counter to target.  TOS is popped.

If TOS is true, sets the bytecode counter to target and leaves TOS on thestack.  Otherwise (TOS is false), TOS is popped.

If TOS is false, sets the bytecode counter to target and leaves TOS on thestack.  Otherwise (TOS is true), TOS is popped.

Set bytecode counter to target.

TOS is an iterator.  Call its next() method.  Ifthis yields a new value, push it on the stack (leaving the iterator belowit).  If the iterator indicates it is exhausted TOS is popped, and the bytecode counter is incremented by delta.

Loads the global named co_names[namei] onto the stack.

Pushes a try block from a try-finally or try-except clause onto the blockstack.  delta points to the finally block or the first except block.

Pushes the address of the next instruction onto the stack and incrementsbytecode counter by delta.  Used for calling the finally block as a“subroutine”.

Pushes a reference to the local co_varnames[var_num] onto the stack.

Stores TOS into the local co_varnames[var_num].

Deletes local co_varnames[var_num].

Pushes a reference to the cell contained in slot i of the cell and freevariable storage.  The name of the variable is co_cellvars[i] if i isless than the length of co_cellvars.  Otherwise it is co_freevars[i -len(co_cellvars)].

Loads the cell contained in slot i of the cell and free variable storage.Pushes a reference to the object the cell contains on the stack.

Much like LOAD_DEREF but first checks the locals dictionary beforeconsulting the cell.  This is used for loading free variables in classbodies.

Stores TOS into the cell contained in slot i of the cell and free variablestorage.

Empties the cell contained in slot i of the cell and free variable storage.Used by the del statement.

Raises an exception using one of the 3 forms of the raise statement,depending on the value of argc:

Calls a callable object with positional arguments.argc indicates the number of positional arguments.The top of the stack contains positional arguments, with the right-mostargument on top.  Below the arguments is a callable object to call.CALL_FUNCTION pops all arguments and the callable object off the stack,calls the callable object with those arguments, and pushes the return valuereturned by the callable object.

Calls a callable object with positional (if any) and keyword arguments.argc indicates the total number of positional and keyword arguments.The top element on the stack contains a tuple of keyword argument names.Below that are keyword arguments in the order corresponding to the tuple.Below that are positional arguments, with the right-most parameter ontop.  Below the arguments is a callable object to call.CALL_FUNCTION_KW pops all arguments and the callable object off the stack,calls the callable object with those arguments, and pushes the return valuereturned by the callable object.

Calls a callable object with variable set of positional and keywordarguments.  If the lowest bit of flags is set, the top of the stackcontains a mapping object containing additional keyword arguments.Below that is an iterable object containing positional arguments anda callable object to call.  BUILD_MAP_UNPACK_WITH_CALL andBUILD_TUPLE_UNPACK_WITH_CALL can be used for merging multiplemapping objects and iterables containing arguments.Before the callable is called, the mapping object and iterable objectare each “unpacked” and their contents passed in as keyword andpositional arguments respectively.CALL_FUNCTION_EX pops all arguments and the callable object off the stack,calls the callable object with those arguments, and pushes the return valuereturned by the callable object.

Loads a method named co_names[namei] from the TOS object. TOS is popped.This bytecode distinguishes two cases: if TOS has a method with the correctname, the bytecode pushes the unbound method and TOS. TOS will be used asthe first argument (self) by CALL_METHOD when calling theunbound method. Otherwise, NULL and the object return by the attributelookup are pushed.

Calls a method.  argc is the number of positional arguments.Keyword arguments are not supported.  This opcode is designed to be usedwith LOAD_METHOD.  Positional arguments are on top of the stack.Below them, the two items described in LOAD_METHOD are on thestack (either self and an unbound method object or NULL and anarbitrary callable). All of them are popped and the return value is pushed.

Pushes a new function object on the stack.  From bottom to top, the consumedstack must consist of values if the argument carries a specified flag value

Pushes a slice object on the stack.  argc must be 2 or 3.  If it is 2,slice(TOS1, TOS) is pushed; if it is 3, slice(TOS2, TOS1, TOS) ispushed. See the slice() built-in function for more information.

Prefixes any opcode which has an argument too big to fit into the default onebyte. ext holds an additional byte which act as higher bits in the argument.For each opcode, at most three prefixal EXTENDED_ARG are allowed, formingan argument from two-byte to four-byte.

Used for implementing formatted literal strings (f-strings).  Popsan optional fmt_spec from the stack, then a required value.flags is interpreted as follows:

This is not really an opcode.  It identifies the dividing line betweenopcodes which don’t use their argument and those that do(< HAVE_ARGUMENT and >= HAVE_ARGUMENT, respectively).

整理不易,點個讚叭,(#^.^#)

相關焦點

  • Python程序執行過程與字節碼
    程序寫好後,只需敲下 python 命令,便可將程序啟動起來並開始執行:$ python some-program.py那麼,一個文本形式的 .py 文件,是如何一步步轉換為能夠被 CPU 執行的機器指令的呢?
  • Python代碼可以加密碼?Python字節碼告訴你!
    眾所周知,執行Python程序可以直接使用python.exe命令,如下所示:看到python直接執行了abc.py,可能很多同學認為python是解釋執行abc.py的,其實不然。如果要真是解釋執行,那效率慢的就沒法用了。實際上,Python與Java一樣,也是玩字節碼出身。Java的字節碼叫Java ByteCode,Python的字節碼叫Python ByteCode。
  • 從1+1=2來理解Java字節碼
    本著複習和鞏固的態度,我決定來編譯一個簡單的類文件來分析Java的字節碼內容,來幫助理解和鞏固Java字節碼知識,希望也對閱讀本文的你有所幫助。1.基礎信息上述結果刪除了部分不影響解析的冗餘信息,接下來我們便來解析字節碼的結果。
  • Python老手告訴你的應用總結:中字節、字符串和編碼
    Python中的字節碼用b'xxx'的形式表示。x可以用字符表示,也可以用ASCII編碼形式\xnn表示,nn從00-ff(十六進位)共256種字符。字節通過某種編碼形式就可以轉化為相應的字符。字節通過encode()方法傳入編碼方式就可以轉化為字符,而字符通過decode()方法就可以轉化為字節:我們可以看到用不同的編碼方式解析出來的字符和字節的方式是完全不同,如果編碼和解碼用了不同的編碼方式,就會產生亂碼,甚至轉換失敗。
  • 實例教程,用python實現字節碼編譯器和解釋器
    實現由原始碼到字節碼的轉化,然後才能執行。本文中蟲蟲以CPython 3.6位元組碼為實例,實現一個我們自己的字節碼編譯器和解釋器,以此來熟悉基本的編譯器工作原理(),當然如果想深入理論學習,建議大家去學習了《編譯原理》這本教材。
  • python解釋器到底是什麼?
    有很多入門學習python的同學都沒有搞清python解釋器是怎麼回事,所以今天在這裡追根溯源的解釋一下。 計算機程式語言 從計算機程式語言說起,它主要分為三類:機器語言、彙編語言、高級語言。
  • 給妹子講python-S01E08理清python中的字符編碼方法
    前文傳送門:給妹子講python-S01E01好用的列表給妹子講python-S01E02學會用字典給妹子講python-S01E03元組的使用給妹子講python-S01E04容器遍歷和列表解析式給妹子講python-S01E05字符串的基本用法給妹子講python-S01E06字符串用法進階給妹子講python-S01E07字符編碼歷史觀:從ASCII到Unicode【要點搶先看】1.python中編、解碼的本質是文本字符串和字節字符串的相互轉換
  • 這一次,徹底弄懂 Java 字節碼文件!
    Java字節碼整體結構如下圖所示,以下圖示以不同緯度展示了字節碼結構中所包含的關鍵內容。Java字節碼整體結構圖:完整的Java字節碼結構圖:接下來結合十六進位格式的 class 文件,參照 Java字節碼文件來剖析下都包含了哪些內容。
  • Java默認構造方法在字節碼的實現
    方法在程序的重要性不言而喻,了解方法在字節碼中的表達能夠使我們開發做到更加心中有數。字節碼講解先看接下來的8個字節「00 01 00 07 00 08 00 01」分別表示訪問標識、名稱索引、描述符索引、屬性數量,結合常量池(索引都是指向常量池)與標識表得出結果分別為:public、<init>、()V、1。
  • 一文讓你明白 Java 字節碼
    從我們寫的java文件到通過編譯器編譯成java字節碼文件(也就是.class文件),這個過程是java編譯過程;而我們的java虛擬機執行的就是字節碼文件。不論該字節碼文件來自何方,由哪種編譯器編譯,甚至是手寫字節碼文件,只要符合java虛擬機的規範,那麼它就能夠執行該字節碼文件。那麼本文主要講講java字節碼文件相關知識。
  • 字節碼層面理解try、catch、finally
    面試中經常有關於try、catch、finally相關的問題,今天從字節碼層面了解他們的運行流程。在這裡我們通過jclasslib查看編譯後的字節碼,並找到方法的字節碼指令,如下圖:右邊被圈中的就是test()方法執行的字節碼指令,字節碼指令較長,接下來一部分一部分的分析。
  • python基礎學習—04字符串與編碼
    二、常見編碼2.1  ASCII碼中文名:美國信息交換標準碼英文名:American Standard Code for Information Interchange基本簡介:ASCII碼是最早的計算機編碼,主要用於表示英文字符、數字和一些標點符號下面是ASCII表:ASCII值控制字符
  • python字符的編碼與解碼
    8個二進位位組成1個字節(Byte),1024位元組(Byte)也就是1KB,1024KB是1M,這就是我們平常說的文件大小的單位(M),比如這個圖片大小5M。既然計算機是通過二進位的數字來識別不同字符的,那不同的字符該用多少個1和0,又該以什麼樣的順序來排列呢?
  • 我算是白學Python了,現在才知道原來Python是可以編譯的
    事實上,Python和Java的解釋方式是相同的,只是我們表面上看Python是直接解釋原始碼,而實際上python解釋器只會加載字節碼。細心的小夥伴肯定發現了這一點,當我們import某個模塊時,總是會在模塊所在的目錄創建一個__pycache__目錄,裡面存放著被加載模塊的字節碼文件。
  • 零基礎學習Python_組織結構和range()函數
    python項目的組織結構一.工程結構先大概了解一下python基本運行機制。Python程序運行時不需要編譯成二進位代碼,而直接從源碼運行程序,簡單來說是,Python解釋器將源碼轉換為字節碼,然後再由解釋器來執行這些字節碼。
  • Fluent Python - Part4 文本和字節序列
    人類使用文本,計算機使用字節序列--- Esther Nam 和 Travis Fischer本章內容基本沒啥用,平常也基本接觸不到多編碼類型的文本處理
  • JAVA字節碼的應用實例,長見識了
    雖然許多字節碼很簡單,但上面的上半行中的字節很複雜且具體到Java。字節碼的長度是一到五字節,因此它們的名字Java助記符使用前綴是32位是整數,A為參考地址,S為16位整數(短),和乙8位字節。我們使用是對於一個16位常量的8位常數和II6。
  • 一文搞懂 JVM 字節碼執行引擎
    學習導圖一.為什麼要學習字節碼執行引擎?代碼編譯的結果從本地機器碼轉變為字節碼,是存儲格式發展的一小步,卻是程式語言發展的一大步首先,拋出靈魂三問:虛擬機在執行代碼的時候,如何找到正確的方法呢?如何執行方法內的字節碼呢?執行代碼時涉及的內存結構有哪些呢?
  • Python高效編程之88條軍規(1):編碼規範、字節序列與字符串
    關於PEP 8的詳細內容,讀者可以查看下面的頁面:https://www.python.org/dev/peps/pep-0008/在Python語言中,空格是有實際意義的。字節序列與字符串都支持加號(+)運算,也就是說,可以用加號分別將字節序列和字符串連接起來,看下面的代碼:print(b'hello ' + b' world')print('hello ' + 'world')b'hello world'hello world但是不能將字節序列和字符串相加
  • python socket實戰(二)
    )佔用多少字節的內存offset = calcsize(fmt)msg = "我正在學習python的網絡編程。"'i',浮點型數字是'f',一個ascii碼字符是's'。下表是常見到python類型、字節和格式符號到對應表。