我正在尝试将一些导入行插入到 python 源文件中,但理想情况下我希望将它们放在初始文档字符串之后。假设我像这样将文件加载到 lines 变量中:
lines = open('filename.py').readlines()
如何找到文档字符串结束的行号?
请您参考如下方法:
您可以使用 python 的标记化模块,而不是使用正则表达式或依赖特定格式。
import tokenize
f=open(filename)
insert_index = None
for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):
if tok == tokenize.COMMENT:
continue
elif tok == tokenize.STRING:
insert_index = erow, ecol
break
else:
break # No docstring found
这样你甚至可以处理病理情况,例如:
# Comment
# """Not the real docstring"""
' this is the module\'s \
docstring, containing:\
""" and having code on the same line following it:'; this_is_code=42
完全按照 python 处理它们的方式。
