tokenize — Python 原始碼的標記器

原始碼: Lib/tokenize.py


tokenize 模組提供了一個用 Python 實現的 Python 原始碼詞法掃描器。此模組中的掃描器也會將註釋作為標記返回,這使得它對實現“漂亮的印表機”(包括螢幕顯示的顏色器)非常有用。

為了簡化標記流處理,所有運算子分隔符標記以及Ellipsis都使用通用的OP標記型別返回。可以透過檢查從tokenize.tokenize()返回的命名元組上的exact_type屬性來確定確切的型別。

警告

請注意,此模組中的函式僅設計用於解析語法上有效的 Python 程式碼(使用ast.parse()解析時不會引發錯誤的程式碼)。當提供無效的 Python 程式碼時,此模組中函式的行為是未定義的,並且可能隨時更改。

標記化輸入

主要入口點是一個生成器

tokenize.tokenize(readline)

tokenize() 生成器需要一個引數 readline,它必須是一個可呼叫物件,提供與檔案物件的 io.IOBase.readline() 方法相同的介面。每次呼叫該函式都應返回一行位元組輸入。

生成器產生包含以下成員的5元組:標記型別;標記字串;指定標記在源中開始的行和列的2元組(srow, scol);指定標記在源中結束的行和列的2元組(erow, ecol);以及找到該標記的行。傳遞的行(最後一個元組項)是 物理 行。5元組以命名元組的形式返回,其欄位名為:type string start end line

返回的命名元組有一個額外的屬性exact_type,其中包含OP標記的確切運算子型別。對於所有其他標記型別,exact_type等於命名元組的type欄位。

3.1 版本中的變化: 增加了對命名元組的支援。

3.3 版本中的變化: 增加了對 exact_type 的支援。

tokenize() 根據 PEP 263 查詢 UTF-8 BOM 或編碼 cookie 來確定檔案的源編碼。

tokenize.generate_tokens(readline)

標記化源,讀取 Unicode 字串而不是位元組。

tokenize() 類似,readline 引數是一個可呼叫物件,返回一行輸入。然而,generate_tokens() 期望 readline 返回一個 str 物件而不是位元組。

結果是一個產生命名元組的迭代器,與 tokenize() 完全相同。它不產生 ENCODING 標記。

token 模組中的所有常量也從 tokenize 匯出。

還提供了一個函式來反轉標記化過程。這對於建立標記化指令碼、修改標記流並寫回修改後的指令碼的工具很有用。

tokenize.untokenize(iterable)

將標記轉換回 Python 原始碼。iterable 必須返回至少包含兩個元素的序列:標記型別和標記字串。任何額外的序列元素都將被忽略。

結果保證可以重新標記化以匹配輸入,從而確保轉換無損且往返一致。此保證僅適用於標記型別和標記字串,因為標記之間的間距(列位置)可能會改變。

它返回位元組,使用 ENCODING 標記編碼,該標記是 tokenize() 輸出的第一個標記序列。如果輸入中沒有編碼標記,則返回一個 str。

tokenize() 需要檢測其標記化原始檔的編碼。它用於此目的的函式可用

tokenize.detect_encoding(readline)

detect_encoding() 函式用於檢測應該用於解碼 Python 原始檔的編碼。它需要一個引數 readline,與 tokenize() 生成器相同。

它最多會呼叫readline兩次,並返回使用的編碼(作為字串)以及它已讀取的任何行(未從位元組解碼)的列表。

它根據 PEP 263 中指定的 UTF-8 BOM 或編碼 cookie 的存在來檢測編碼。如果 BOM 和 cookie 都存在但存在分歧,則會引發 SyntaxError。請注意,如果找到 BOM,則返回 'utf-8-sig' 作為編碼。

如果未指定編碼,則將返回預設值 'utf-8'

使用 open() 開啟 Python 原始檔:它使用 detect_encoding() 來檢測檔案編碼。

tokenize.open(filename)

使用 detect_encoding() 檢測到的編碼以只讀模式開啟檔案。

在 3.2 版本加入。

exception tokenize.TokenError

當一個文件字串或可能跨多行的表示式在檔案中的任何地方都沒有完成時引發,例如

"""Beginning of
docstring

[1,
 2,
 3

命令列用法

在 3.3 版本加入。

tokenize 模組可以作為指令碼從命令列執行。它很簡單,如下所示

python -m tokenize [-e] [filename.py]

接受以下選項

-h, --help

顯示此幫助資訊並退出

-e, --exact

使用確切型別顯示標記名稱

如果指定了 filename.py,其內容將被標記化到標準輸出。否則,標記化將在標準輸入上執行。

示例

將浮點文字轉換為 Decimal 物件的指令碼重寫器示例

from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
from io import BytesIO

def decistmt(s):
    """Substitute Decimals for floats in a string of statements.

    >>> from decimal import Decimal
    >>> s = 'print(+21.3e-5*-.1234/81.7)'
    >>> decistmt(s)
    "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"

    The format of the exponent is inherited from the platform C library.
    Known cases are "e-007" (Windows) and "e-07" (not Windows).  Since
    we're only showing 12 digits, and the 13th isn't close to 5, the
    rest of the output should be platform-independent.

    >>> exec(s)  #doctest: +ELLIPSIS
    -3.21716034272e-0...7

    Output from calculations with Decimal should be identical across all
    platforms.

    >>> exec(decistmt(s))
    -3.217160342717258261933904529E-7
    """
    result = []
    g = tokenize(BytesIO(s.encode('utf-8')).readline)  # tokenize the string
    for toknum, tokval, _, _, _ in g:
        if toknum == NUMBER and '.' in tokval:  # replace NUMBER tokens
            result.extend([
                (NAME, 'Decimal'),
                (OP, '('),
                (STRING, repr(tokval)),
                (OP, ')')
            ])
        else:
            result.append((toknum, tokval))
    return untokenize(result).decode('utf-8')

從命令列進行標記化的示例。指令碼

def say_hello():
    print("Hello, World!")

say_hello()

將被標記為以下輸出,其中第一列是找到標記的行/列座標範圍,第二列是標記的名稱,最後一列是標記的值(如果有)

$ python -m tokenize hello.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,3:            NAME           'def'
1,4-1,13:           NAME           'say_hello'
1,13-1,14:          OP             '('
1,14-1,15:          OP             ')'
1,15-1,16:          OP             ':'
1,16-1,17:          NEWLINE        '\n'
2,0-2,4:            INDENT         '    '
2,4-2,9:            NAME           'print'
2,9-2,10:           OP             '('
2,10-2,25:          STRING         '"Hello, World!"'
2,25-2,26:          OP             ')'
2,26-2,27:          NEWLINE        '\n'
3,0-3,1:            NL             '\n'
4,0-4,0:            DEDENT         ''
4,0-4,9:            NAME           'say_hello'
4,9-4,10:           OP             '('
4,10-4,11:          OP             ')'
4,11-4,12:          NEWLINE        '\n'
5,0-5,0:            ENDMARKER      ''

確切的標記型別名稱可以使用 -e 選項顯示

$ python -m tokenize -e hello.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,3:            NAME           'def'
1,4-1,13:           NAME           'say_hello'
1,13-1,14:          LPAR           '('
1,14-1,15:          RPAR           ')'
1,15-1,16:          COLON          ':'
1,16-1,17:          NEWLINE        '\n'
2,0-2,4:            INDENT         '    '
2,4-2,9:            NAME           'print'
2,9-2,10:           LPAR           '('
2,10-2,25:          STRING         '"Hello, World!"'
2,25-2,26:          RPAR           ')'
2,26-2,27:          NEWLINE        '\n'
3,0-3,1:            NL             '\n'
4,0-4,0:            DEDENT         ''
4,0-4,9:            NAME           'say_hello'
4,9-4,10:           LPAR           '('
4,10-4,11:          RPAR           ')'
4,11-4,12:          NEWLINE        '\n'
5,0-5,0:            ENDMARKER      ''

以程式設計方式標記檔案,使用 generate_tokens() 讀取 Unicode 字串而不是位元組的示例

import tokenize

with tokenize.open('hello.py') as f:
    tokens = tokenize.generate_tokens(f.readline)
    for token in tokens:
        print(token)

或者直接使用 tokenize() 讀取位元組

import tokenize

with open('hello.py', 'rb') as f:
    tokens = tokenize.tokenize(f.readline)
    for token in tokens:
        print(token)