lib64
/
python3.6
/
Go to Home Directory
+
Upload
Create File
root@0UT1S:~$
Execute
By Order of Mr.0UT1S
[DIR] ..
N/A
[DIR] __pycache__
N/A
[DIR] asyncio
N/A
[DIR] collections
N/A
[DIR] concurrent
N/A
[DIR] config-3.6m-x86_64-linux-gnu
N/A
[DIR] ctypes
N/A
[DIR] curses
N/A
[DIR] dbm
N/A
[DIR] distutils
N/A
[DIR] email
N/A
[DIR] encodings
N/A
[DIR] ensurepip
N/A
[DIR] html
N/A
[DIR] http
N/A
[DIR] importlib
N/A
[DIR] json
N/A
[DIR] lib-dynload
N/A
[DIR] lib2to3
N/A
[DIR] logging
N/A
[DIR] multiprocessing
N/A
[DIR] pydoc_data
N/A
[DIR] site-packages
N/A
[DIR] sqlite3
N/A
[DIR] test
N/A
[DIR] unittest
N/A
[DIR] urllib
N/A
[DIR] venv
N/A
[DIR] wsgiref
N/A
[DIR] xml
N/A
[DIR] xmlrpc
N/A
__future__.py
4.73 KB
Rename
Delete
__phello__.foo.py
64 bytes
Rename
Delete
_bootlocale.py
1.27 KB
Rename
Delete
_collections_abc.py
25.77 KB
Rename
Delete
_compat_pickle.py
8.54 KB
Rename
Delete
_compression.py
5.21 KB
Rename
Delete
_dummy_thread.py
5.00 KB
Rename
Delete
_markupbase.py
14.26 KB
Rename
Delete
_osx_support.py
18.69 KB
Rename
Delete
_pydecimal.py
224.83 KB
Rename
Delete
_pyio.py
86.03 KB
Rename
Delete
_sitebuiltins.py
3.04 KB
Rename
Delete
_strptime.py
24.17 KB
Rename
Delete
_sysconfigdata_dm_linux_x86_64-linux-gnu.py
29.48 KB
Rename
Delete
_sysconfigdata_m_linux_x86_64-linux-gnu.py
29.66 KB
Rename
Delete
_threading_local.py
7.04 KB
Rename
Delete
_weakrefset.py
5.57 KB
Rename
Delete
abc.py
8.52 KB
Rename
Delete
aifc.py
31.69 KB
Rename
Delete
antigravity.py
477 bytes
Rename
Delete
argparse.py
88.25 KB
Rename
Delete
ast.py
11.88 KB
Rename
Delete
asynchat.py
11.06 KB
Rename
Delete
asyncore.py
19.69 KB
Rename
Delete
base64.py
19.91 KB
Rename
Delete
bdb.py
23.00 KB
Rename
Delete
binhex.py
13.63 KB
Rename
Delete
bisect.py
2.53 KB
Rename
Delete
bz2.py
12.19 KB
Rename
Delete
cProfile.py
5.25 KB
Rename
Delete
calendar.py
22.67 KB
Rename
Delete
cgi.py
36.35 KB
Rename
Delete
cgitb.py
11.74 KB
Rename
Delete
chunk.py
5.30 KB
Rename
Delete
cmd.py
14.51 KB
Rename
Delete
code.py
10.37 KB
Rename
Delete
codecs.py
35.43 KB
Rename
Delete
codeop.py
5.85 KB
Rename
Delete
colorsys.py
3.97 KB
Rename
Delete
compileall.py
11.84 KB
Rename
Delete
configparser.py
52.34 KB
Rename
Delete
contextlib.py
12.85 KB
Rename
Delete
copy.py
8.61 KB
Rename
Delete
copyreg.py
6.84 KB
Rename
Delete
crypt.py
1.82 KB
Rename
Delete
csv.py
15.80 KB
Rename
Delete
datetime.py
80.11 KB
Rename
Delete
decimal.py
320 bytes
Rename
Delete
difflib.py
82.40 KB
Rename
Delete
dis.py
17.71 KB
Rename
Delete
doctest.py
101.94 KB
Rename
Delete
dummy_threading.py
2.75 KB
Rename
Delete
enum.py
32.82 KB
Rename
Delete
filecmp.py
9.60 KB
Rename
Delete
fileinput.py
14.13 KB
Rename
Delete
fnmatch.py
3.09 KB
Rename
Delete
formatter.py
14.79 KB
Rename
Delete
fractions.py
23.08 KB
Rename
Delete
ftplib.py
34.78 KB
Rename
Delete
functools.py
30.61 KB
Rename
Delete
genericpath.py
4.64 KB
Rename
Delete
getopt.py
7.31 KB
Rename
Delete
getpass.py
5.85 KB
Rename
Delete
gettext.py
21.03 KB
Rename
Delete
glob.py
5.51 KB
Rename
Delete
gzip.py
19.86 KB
Rename
Delete
hashlib.py
8.59 KB
Rename
Delete
heapq.py
22.39 KB
Rename
Delete
hmac.py
6.23 KB
Rename
Delete
imaplib.py
52.05 KB
Rename
Delete
imghdr.py
3.71 KB
Rename
Delete
imp.py
10.42 KB
Rename
Delete
inspect.py
114.22 KB
Rename
Delete
io.py
3.43 KB
Rename
Delete
ipaddress.py
75.99 KB
Rename
Delete
keyword.py
2.17 KB
Rename
Delete
linecache.py
5.19 KB
Rename
Delete
locale.py
75.49 KB
Rename
Delete
lzma.py
12.68 KB
Rename
Delete
macpath.py
5.83 KB
Rename
Delete
macurl2path.py
2.67 KB
Rename
Delete
mailbox.py
76.78 KB
Rename
Delete
mailcap.py
8.85 KB
Rename
Delete
mimetypes.py
20.55 KB
Rename
Delete
modulefinder.py
22.49 KB
Rename
Delete
netrc.py
5.55 KB
Rename
Delete
nntplib.py
42.07 KB
Rename
Delete
ntpath.py
22.55 KB
Rename
Delete
nturl2path.py
2.39 KB
Rename
Delete
numbers.py
10.00 KB
Rename
Delete
opcode.py
5.69 KB
Rename
Delete
operator.py
10.61 KB
Rename
Delete
optparse.py
58.96 KB
Rename
Delete
os.py
36.65 KB
Rename
Delete
pathlib.py
47.83 KB
Rename
Delete
pdb.py
59.88 KB
Rename
Delete
pickle.py
54.39 KB
Rename
Delete
pickletools.py
89.62 KB
Rename
Delete
pipes.py
8.71 KB
Rename
Delete
pkgutil.py
20.82 KB
Rename
Delete
platform.py
46.11 KB
Rename
Delete
plistlib.py
31.53 KB
Rename
Delete
poplib.py
14.61 KB
Rename
Delete
posixpath.py
15.40 KB
Rename
Delete
pprint.py
20.37 KB
Rename
Delete
profile.py
21.51 KB
Rename
Delete
pstats.py
25.94 KB
Rename
Delete
pty.py
4.65 KB
Rename
Delete
py_compile.py
7.01 KB
Rename
Delete
pyclbr.py
13.24 KB
Rename
Delete
pydoc.py
101.08 KB
Rename
Delete
queue.py
8.57 KB
Rename
Delete
quopri.py
7.09 KB
Rename
Delete
random.py
26.80 KB
Rename
Delete
re.py
15.19 KB
Rename
Delete
reprlib.py
5.21 KB
Rename
Delete
rlcompleter.py
6.93 KB
Rename
Delete
runpy.py
11.68 KB
Rename
Delete
sched.py
6.36 KB
Rename
Delete
secrets.py
1.99 KB
Rename
Delete
selectors.py
18.98 KB
Rename
Delete
shelve.py
8.32 KB
Rename
Delete
shlex.py
12.65 KB
Rename
Delete
shutil.py
39.87 KB
Rename
Delete
signal.py
2.07 KB
Rename
Delete
site.py
20.77 KB
Rename
Delete
smtpd.py
33.91 KB
Rename
Delete
smtplib.py
43.18 KB
Rename
Delete
sndhdr.py
6.92 KB
Rename
Delete
socket.py
26.80 KB
Rename
Delete
socketserver.py
26.38 KB
Rename
Delete
sre_compile.py
18.88 KB
Rename
Delete
sre_constants.py
6.66 KB
Rename
Delete
sre_parse.py
35.68 KB
Rename
Delete
ssl.py
43.47 KB
Rename
Delete
stat.py
4.92 KB
Rename
Delete
statistics.py
20.19 KB
Rename
Delete
string.py
11.52 KB
Rename
Delete
stringprep.py
12.61 KB
Rename
Delete
struct.py
257 bytes
Rename
Delete
subprocess.py
60.88 KB
Rename
Delete
sunau.py
17.67 KB
Rename
Delete
symbol.py
2.07 KB
Rename
Delete
symtable.py
7.11 KB
Rename
Delete
sysconfig.py
24.29 KB
Rename
Delete
tabnanny.py
11.14 KB
Rename
Delete
tarfile.py
104.88 KB
Rename
Delete
telnetlib.py
22.59 KB
Rename
Delete
tempfile.py
27.41 KB
Rename
Delete
textwrap.py
19.10 KB
Rename
Delete
this.py
1003 bytes
Rename
Delete
threading.py
48.96 KB
Rename
Delete
timeit.py
13.03 KB
Rename
Delete
token.py
3.00 KB
Rename
Delete
tokenize.py
28.80 KB
Rename
Delete
trace.py
28.06 KB
Rename
Delete
traceback.py
22.91 KB
Rename
Delete
tracemalloc.py
16.27 KB
Rename
Delete
tty.py
879 bytes
Rename
Delete
types.py
8.66 KB
Rename
Delete
typing.py
78.39 KB
Rename
Delete
uu.py
6.60 KB
Rename
Delete
uuid.py
23.46 KB
Rename
Delete
warnings.py
18.05 KB
Rename
Delete
wave.py
17.29 KB
Rename
Delete
weakref.py
19.99 KB
Rename
Delete
webbrowser.py
21.26 KB
Rename
Delete
xdrlib.py
5.77 KB
Rename
Delete
zipapp.py
6.99 KB
Rename
Delete
zipfile.py
78.05 KB
Rename
Delete
"""Tokenization help for Python programs. tokenize(readline) is a generator that breaks a stream of bytes into Python tokens. It decodes the bytes according to PEP-0263 for determining source file encoding. It accepts a readline-like method which is called repeatedly to get the next line of input (or b"" for EOF). It generates 5-tuples with these members: the token type (see token.py) the token (a string) the starting (row, column) indices of the token (a 2-tuple of ints) the ending (row, column) indices of the token (a 2-tuple of ints) the original line (string) It is designed to match the working of the Python tokenizer exactly, except that it produces COMMENT tokens for comments and gives type OP for all operators. Additionally, all token lists start with an ENCODING token which tells you which encoding was used to decode the bytes stream. """ __author__ = 'Ka-Ping Yee <ping@lfw.org>' __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, ' 'Skip Montanaro, Raymond Hettinger, Trent Nelson, ' 'Michael Foord') from builtins import open as _builtin_open from codecs import lookup, BOM_UTF8 import collections from io import TextIOWrapper from itertools import chain import itertools as _itertools import re import sys from token import * cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII) blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII) import token __all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding", "NL", "untokenize", "ENCODING", "TokenInfo"] del token COMMENT = N_TOKENS tok_name[COMMENT] = 'COMMENT' NL = N_TOKENS + 1 tok_name[NL] = 'NL' ENCODING = N_TOKENS + 2 tok_name[ENCODING] = 'ENCODING' N_TOKENS += 3 EXACT_TOKEN_TYPES = { '(': LPAR, ')': RPAR, '[': LSQB, ']': RSQB, ':': COLON, ',': COMMA, ';': SEMI, '+': PLUS, '-': MINUS, '*': STAR, '/': SLASH, '|': VBAR, '&': AMPER, '<': LESS, '>': GREATER, '=': EQUAL, '.': DOT, '%': PERCENT, '{': LBRACE, '}': RBRACE, '==': EQEQUAL, '!=': NOTEQUAL, '<=': LESSEQUAL, '>=': GREATEREQUAL, '~': TILDE, '^': CIRCUMFLEX, '<<': LEFTSHIFT, '>>': RIGHTSHIFT, '**': DOUBLESTAR, '+=': PLUSEQUAL, '-=': MINEQUAL, '*=': STAREQUAL, '/=': SLASHEQUAL, '%=': PERCENTEQUAL, '&=': AMPEREQUAL, '|=': VBAREQUAL, '^=': CIRCUMFLEXEQUAL, '<<=': LEFTSHIFTEQUAL, '>>=': RIGHTSHIFTEQUAL, '**=': DOUBLESTAREQUAL, '//': DOUBLESLASH, '//=': DOUBLESLASHEQUAL, '@': AT, '@=': ATEQUAL, } class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')): def __repr__(self): annotated_type = '%d (%s)' % (self.type, tok_name[self.type]) return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' % self._replace(type=annotated_type)) @property def exact_type(self): if self.type == OP and self.string in EXACT_TOKEN_TYPES: return EXACT_TOKEN_TYPES[self.string] else: return self.type def group(*choices): return '(' + '|'.join(choices) + ')' def any(*choices): return group(*choices) + '*' def maybe(*choices): return group(*choices) + '?' # Note: we use unicode matching for names ("\w") but ascii matching for # number literals. Whitespace = r'[ \f\t]*' Comment = r'#[^\r\n]*' Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment) Name = r'\w+' Hexnumber = r'0[xX](?:_?[0-9a-fA-F])+' Binnumber = r'0[bB](?:_?[01])+' Octnumber = r'0[oO](?:_?[0-7])+' Decnumber = r'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)' Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber) Exponent = r'[eE][-+]?[0-9](?:_?[0-9])*' Pointfloat = group(r'[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?', r'\.[0-9](?:_?[0-9])*') + maybe(Exponent) Expfloat = r'[0-9](?:_?[0-9])*' + Exponent Floatnumber = group(Pointfloat, Expfloat) Imagnumber = group(r'[0-9](?:_?[0-9])*[jJ]', Floatnumber + r'[jJ]') Number = group(Imagnumber, Floatnumber, Intnumber) # Return the empty string, plus all of the valid string prefixes. def _all_string_prefixes(): # The valid string prefixes. Only contain the lower case versions, # and don't contain any permuations (include 'fr', but not # 'rf'). The various permutations will be generated. _valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr'] # if we add binary f-strings, add: ['fb', 'fbr'] result = set(['']) for prefix in _valid_string_prefixes: for t in _itertools.permutations(prefix): # create a list with upper and lower versions of each # character for u in _itertools.product(*[(c, c.upper()) for c in t]): result.add(''.join(u)) return result def _compile(expr): return re.compile(expr, re.UNICODE) # Note that since _all_string_prefixes includes the empty string, # StringPrefix can be the empty string (making it optional). StringPrefix = group(*_all_string_prefixes()) # Tail end of ' string. Single = r"[^'\\]*(?:\\.[^'\\]*)*'" # Tail end of " string. Double = r'[^"\\]*(?:\\.[^"\\]*)*"' # Tail end of ''' string. Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" # Tail end of """ string. Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' Triple = group(StringPrefix + "'''", StringPrefix + '"""') # Single-line ' or " string. String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'", StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"') # Because of leftmost-then-longest match semantics, be sure to put the # longest operators first (e.g., if = came before ==, == would get # recognized as two instances of =). Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=", r"//=?", r"->", r"[+\-*/%&@|^=<>]=?", r"~") Bracket = '[][(){}]' Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]') Funny = group(Operator, Bracket, Special) PlainToken = group(Number, Funny, String, Name) Token = Ignore + PlainToken # First (or only) line of ' or " string. ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" + group("'", r'\\\r?\n'), StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' + group('"', r'\\\r?\n')) PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple) PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name) # For a given string prefix plus quotes, endpats maps it to a regex # to match the remainder of that string. _prefix can be empty, for # a normal single or triple quoted string (with no prefix). endpats = {} for _prefix in _all_string_prefixes(): endpats[_prefix + "'"] = Single endpats[_prefix + '"'] = Double endpats[_prefix + "'''"] = Single3 endpats[_prefix + '"""'] = Double3 # A set of all of the single and triple quoted string prefixes, # including the opening quotes. single_quoted = set() triple_quoted = set() for t in _all_string_prefixes(): for u in (t + '"', t + "'"): single_quoted.add(u) for u in (t + '"""', t + "'''"): triple_quoted.add(u) tabsize = 8 class TokenError(Exception): pass class StopTokenizing(Exception): pass class Untokenizer: def __init__(self): self.tokens = [] self.prev_row = 1 self.prev_col = 0 self.encoding = None def add_whitespace(self, start): row, col = start if row < self.prev_row or row == self.prev_row and col < self.prev_col: raise ValueError("start ({},{}) precedes previous end ({},{})" .format(row, col, self.prev_row, self.prev_col)) row_offset = row - self.prev_row if row_offset: self.tokens.append("\\\n" * row_offset) self.prev_col = 0 col_offset = col - self.prev_col if col_offset: self.tokens.append(" " * col_offset) def untokenize(self, iterable): it = iter(iterable) indents = [] startline = False for t in it: if len(t) == 2: self.compat(t, it) break tok_type, token, start, end, line = t if tok_type == ENCODING: self.encoding = token continue if tok_type == ENDMARKER: break if tok_type == INDENT: indents.append(token) continue elif tok_type == DEDENT: indents.pop() self.prev_row, self.prev_col = end continue elif tok_type in (NEWLINE, NL): startline = True elif startline and indents: indent = indents[-1] if start[1] >= len(indent): self.tokens.append(indent) self.prev_col = len(indent) startline = False self.add_whitespace(start) self.tokens.append(token) self.prev_row, self.prev_col = end if tok_type in (NEWLINE, NL): self.prev_row += 1 self.prev_col = 0 return "".join(self.tokens) def compat(self, token, iterable): indents = [] toks_append = self.tokens.append startline = token[0] in (NEWLINE, NL) prevstring = False for tok in chain([token], iterable): toknum, tokval = tok[:2] if toknum == ENCODING: self.encoding = tokval continue if toknum in (NAME, NUMBER, ASYNC, AWAIT): tokval += ' ' # Insert a space between two consecutive strings if toknum == STRING: if prevstring: tokval = ' ' + tokval prevstring = True else: prevstring = False if toknum == INDENT: indents.append(tokval) continue elif toknum == DEDENT: indents.pop() continue elif toknum in (NEWLINE, NL): startline = True elif startline and indents: toks_append(indents[-1]) startline = False toks_append(tokval) def untokenize(iterable): """Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited input: # Output bytes will tokenize back to the input t1 = [tok[:2] for tok in tokenize(f.readline)] newcode = untokenize(t1) readline = BytesIO(newcode).readline t2 = [tok[:2] for tok in tokenize(readline)] assert t1 == t2 """ ut = Untokenizer() out = ut.untokenize(iterable) if ut.encoding is not None: out = out.encode(ut.encoding) return out def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): return "iso-8859-1" return orig_enc def detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned. """ try: filename = readline.__self__.name except AttributeError: filename = None bom_found = False encoding = None default = 'utf-8' def read_or_stop(): try: return readline() except StopIteration: return b'' def find_cookie(line): try: # Decode as UTF-8. Either the line is an encoding declaration, # in which case it should be pure ASCII, or it must be UTF-8 # per default encoding. line_string = line.decode('utf-8') except UnicodeDecodeError: msg = "invalid or missing encoding declaration" if filename is not None: msg = '{} for {!r}'.format(msg, filename) raise SyntaxError(msg) match = cookie_re.match(line_string) if not match: return None encoding = _get_normal_name(match.group(1)) try: codec = lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter if filename is None: msg = "unknown encoding: " + encoding else: msg = "unknown encoding for {!r}: {}".format(filename, encoding) raise SyntaxError(msg) if bom_found: if encoding != 'utf-8': # This behaviour mimics the Python interpreter if filename is None: msg = 'encoding problem: utf-8' else: msg = 'encoding problem for {!r}: utf-8'.format(filename) raise SyntaxError(msg) encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] encoding = find_cookie(first) if encoding: return encoding, [first] if not blank_re.match(first): return default, [first] second = read_or_stop() if not second: return default, [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return default, [first, second] def open(filename): """Open a file in read only mode using the encoding detected by detect_encoding(). """ buffer = _builtin_open(filename, 'rb') try: encoding, lines = detect_encoding(buffer.readline) buffer.seek(0) text = TextIOWrapper(buffer, encoding, line_buffering=True) text.mode = 'r' return text except: buffer.close() raise def tokenize(readline): """ The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as bytes. Alternatively, readline can be a callable function terminating with StopIteration: readline = open(myfile, 'rb').__next__ # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the logical line; continuation lines are included. The first token sequence will always be an ENCODING token which tells you which encoding was used to decode the bytes stream. """ # This import is here to avoid problems when the itertools module is not # built yet and tokenize is imported. from itertools import chain, repeat encoding, consumed = detect_encoding(readline) rl_gen = iter(readline, b"") empty = repeat(b"") return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding) def _tokenize(readline, encoding): lnum = parenlev = continued = 0 numchars = '0123456789' contstr, needcont = '', 0 contline = None indents = [0] # 'stashed' and 'async_*' are used for async/await parsing stashed = None async_def = False async_def_indent = 0 async_def_nl = False if encoding is not None: if encoding == "utf-8-sig": # BOM will already have been stripped. encoding = "utf-8" yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '') last_line = b'' line = b'' while True: # loop over lines in stream try: # We capture the value of the line variable here because # readline uses the empty string '' to signal end of input, # hence `line` itself will always be overwritten at the end # of this loop. last_line = line line = readline() except StopIteration: line = b'' if encoding is not None: line = line.decode(encoding) lnum += 1 pos, max = 0, len(line) if contstr: # continued string if not line: raise TokenError("EOF in multi-line string", strstart) endmatch = endprog.match(line) if endmatch: pos = end = endmatch.end(0) yield TokenInfo(STRING, contstr + line[:end], strstart, (lnum, end), contline + line) contstr, needcont = '', 0 contline = None elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': yield TokenInfo(ERRORTOKEN, contstr + line, strstart, (lnum, len(line)), contline) contstr = '' contline = None continue else: contstr = contstr + line contline = contline + line continue elif parenlev == 0 and not continued: # new statement if not line: break column = 0 while pos < max: # measure leading whitespace if line[pos] == ' ': column += 1 elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize elif line[pos] == '\f': column = 0 else: break pos += 1 if pos == max: break if line[pos] in '#\r\n': # skip comments or blank lines if line[pos] == '#': comment_token = line[pos:].rstrip('\r\n') nl_pos = pos + len(comment_token) yield TokenInfo(COMMENT, comment_token, (lnum, pos), (lnum, pos + len(comment_token)), line) yield TokenInfo(NL, line[nl_pos:], (lnum, nl_pos), (lnum, len(line)), line) else: yield TokenInfo((NL, COMMENT)[line[pos] == '#'], line[pos:], (lnum, pos), (lnum, len(line)), line) continue if column > indents[-1]: # count indents or dedents indents.append(column) yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line) while column < indents[-1]: if column not in indents: raise IndentationError( "unindent does not match any outer indentation level", ("<tokenize>", lnum, pos, line)) indents = indents[:-1] if async_def and async_def_indent >= indents[-1]: async_def = False async_def_nl = False async_def_indent = 0 yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line) if async_def and async_def_nl and async_def_indent >= indents[-1]: async_def = False async_def_nl = False async_def_indent = 0 else: # continued statement if not line: raise TokenError("EOF in multi-line statement", (lnum, 0)) continued = 0 while pos < max: pseudomatch = _compile(PseudoToken).match(line, pos) if pseudomatch: # scan for tokens start, end = pseudomatch.span(1) spos, epos, pos = (lnum, start), (lnum, end), end if start == end: continue token, initial = line[start:end], line[start] if (initial in numchars or # ordinary number (initial == '.' and token != '.' and token != '...')): yield TokenInfo(NUMBER, token, spos, epos, line) elif initial in '\r\n': if stashed: yield stashed stashed = None if parenlev > 0: yield TokenInfo(NL, token, spos, epos, line) else: yield TokenInfo(NEWLINE, token, spos, epos, line) if async_def: async_def_nl = True elif initial == '#': assert not token.endswith("\n") if stashed: yield stashed stashed = None yield TokenInfo(COMMENT, token, spos, epos, line) elif token in triple_quoted: endprog = _compile(endpats[token]) endmatch = endprog.match(line, pos) if endmatch: # all on one line pos = endmatch.end(0) token = line[start:pos] yield TokenInfo(STRING, token, spos, (lnum, pos), line) else: strstart = (lnum, start) # multiple lines contstr = line[start:] contline = line break # Check up to the first 3 chars of the token to see if # they're in the single_quoted set. If so, they start # a string. # We're using the first 3, because we're looking for # "rb'" (for example) at the start of the token. If # we switch to longer prefixes, this needs to be # adjusted. # Note that initial == token[:1]. # Also note that single quote checking must come after # triple quote checking (above). elif (initial in single_quoted or token[:2] in single_quoted or token[:3] in single_quoted): if token[-1] == '\n': # continued string strstart = (lnum, start) # Again, using the first 3 chars of the # token. This is looking for the matching end # regex for the correct type of quote # character. So it's really looking for # endpats["'"] or endpats['"'], by trying to # skip string prefix characters, if any. endprog = _compile(endpats.get(initial) or endpats.get(token[1]) or endpats.get(token[2])) contstr, needcont = line[start:], 1 contline = line break else: # ordinary string yield TokenInfo(STRING, token, spos, epos, line) elif initial.isidentifier(): # ordinary name if token in ('async', 'await'): if async_def: yield TokenInfo( ASYNC if token == 'async' else AWAIT, token, spos, epos, line) continue tok = TokenInfo(NAME, token, spos, epos, line) if token == 'async' and not stashed: stashed = tok continue if token == 'def': if (stashed and stashed.type == NAME and stashed.string == 'async'): async_def = True async_def_indent = indents[-1] yield TokenInfo(ASYNC, stashed.string, stashed.start, stashed.end, stashed.line) stashed = None if stashed: yield stashed stashed = None yield tok elif initial == '\\': # continued stmt continued = 1 else: if initial in '([{': parenlev += 1 elif initial in ')]}': parenlev -= 1 if stashed: yield stashed stashed = None yield TokenInfo(OP, token, spos, epos, line) else: yield TokenInfo(ERRORTOKEN, line[pos], (lnum, pos), (lnum, pos+1), line) pos += 1 if stashed: yield stashed stashed = None # Add an implicit NEWLINE if the input doesn't end in one if last_line and last_line[-1] not in '\r\n': yield TokenInfo(NEWLINE, '', (lnum - 1, len(last_line)), (lnum - 1, len(last_line) + 1), '') for indent in indents[1:]: # pop remaining indent levels yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '') yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '') # An undocumented, backwards compatible, API for all the places in the standard # library that expect to be able to use tokenize with strings def generate_tokens(readline): return _tokenize(readline, None) def main(): import argparse # Helper error handling routines def perror(message): print(message, file=sys.stderr) def error(message, filename=None, location=None): if location: args = (filename,) + location + (message,) perror("%s:%d:%d: error: %s" % args) elif filename: perror("%s: error: %s" % (filename, message)) else: perror("error: %s" % message) sys.exit(1) # Parse the arguments and options parser = argparse.ArgumentParser(prog='python -m tokenize') parser.add_argument(dest='filename', nargs='?', metavar='filename.py', help='the file to tokenize; defaults to stdin') parser.add_argument('-e', '--exact', dest='exact', action='store_true', help='display token names using the exact type') args = parser.parse_args() try: # Tokenize the input if args.filename: filename = args.filename with _builtin_open(filename, 'rb') as f: tokens = list(tokenize(f.readline)) else: filename = "<stdin>" tokens = _tokenize(sys.stdin.readline, None) # Output the tokenization for token in tokens: token_type = token.type if args.exact: token_type = token.exact_type token_range = "%d,%d-%d,%d:" % (token.start + token.end) print("%-20s%-15s%-15r" % (token_range, tok_name[token_type], token.string)) except IndentationError as err: line, column = err.args[1][1:3] error(err.args[0], filename, (line, column)) except TokenError as err: line, column = err.args[1] error(err.args[0], filename, (line, column)) except SyntaxError as err: error(err, filename) except OSError as err: error(err) except KeyboardInterrupt: print("interrupted\n") except Exception as err: perror("unexpected error: %s" % err) raise if __name__ == "__main__": main()
Save