How to differentiate between “a string” and “a actual code” in python?

╄→尐↘猪︶ㄣ 提交于 2019-11-29 17:05:52

Use the ast module to parse the file properly.

This code prints the line number and column offset of each def statement:

import ast
with open('mymodule.py') as f:
    tree = ast.parse(f.read())
for node in ast.walk(tree):
    if isinstance(node, ast.FunctionDef):
        print node.lineno, node.col_offset

You could use a Regular Expression. To avoid def inside quotes then you can use negative look-arounds:

import re

for line in open('A.py'):
    m = re.search(r"(?!<[\"'])\bdef\b(?![\"'])", line)
    if m:
        print r'@decorator    #<------ inserted code' 

    print line 

However, there might be other occurances of def that you or I can't think of, and if we are not careful we end-up writing the Python parser all over again. @Janne Karila's suggestion of using ast.parse is probably safer in the long term.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!