Skip to content

[3.8] bpo-36654: Add examples for using tokenize module programmically (GH-12947) #18187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 25, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Doc/library/tokenize.rst
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,22 @@ The exact token type names can be displayed using the :option:`-e` option:
4,10-4,11: RPAR ')'
4,11-4,12: NEWLINE '\n'
5,0-5,0: ENDMARKER ''

Example of tokenizing a file programmatically, reading unicode
strings instead of bytes with :func:`generate_tokens`::

import tokenize

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

Or reading bytes directly with :func:`.tokenize`::

import tokenize

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