实现说明
这个文件只在 for token in tokenize.generate_tokens(io.StringIO(source).readline) 里循环。
source、greeting、total、comments 定义在模块顶层,中间不经过函数作用域。
使用要点
tokenize必须先装好——示例直接导入它们。
常见问题
它需要从包仓库拿什么?
这些是真实的依赖:tokenize。缺了就加载不起来。
核心语句
for token in tokenize.generate_tokens(io.StringIO(source).readline):
if token.type == tokenize.COMMENT:
comments.append(token.string)
for comment in comments:
print(" ", comment)
代码示例
import io
import tokenize
source = '''route = "/reports/<id>" # endpoint for the export
greeting = "hi # there" # the # inside quotes stays text
# TODO: paginate the export
total = len(route) # trailing note
'''
comments = []
for token in tokenize.generate_tokens(io.StringIO(source).readline):
if token.type == tokenize.COMMENT:
comments.append(token.string)
print(f"{len(comments)} comments outside strings")
for comment in comments:
print(" ", comment)