如何使用正则表达式跳过docstring

Bar*_*ski 1 python

我正在尝试将一些导入行插入到python源文件中,但我最好将它们放在初始docstring之后.假设我将文件加载到lines变量中,如下所示:

lines = open('filename.py').readlines()
Run Code Online (Sandbox Code Playgroud)

如何找到文档字符串结束的行号?

Bri*_*ian 9

您可以使用python的tokenize模块,而不是使用正则表达式,或依赖于特定的格式.

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
Run Code Online (Sandbox Code Playgroud)

这样你甚至可以处理病态案例,如:

# 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
Run Code Online (Sandbox Code Playgroud)

正如python会处理它们一样.