]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-36654: Add examples for using tokenize module programmically (#12947)
authorWindson yang <wiwindson@outlook.com>
Sat, 25 Jan 2020 19:23:00 +0000 (03:23 +0800)
committerBerker Peksag <berker.peksag@gmail.com>
Sat, 25 Jan 2020 19:23:00 +0000 (22:23 +0300)
Doc/library/tokenize.rst

index b208ba46d17d99de7b4835697ea923fb92f4ff44..96778f23f8f06250c87050e2a0bc2286b9dd001e 100644 (file)
@@ -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)