gpt4 book ai didi

python - python中如何区分 "a string"和 "a actual code"?

转载 作者:行者123 更新时间:2023-11-30 23:36:01 25 4
gpt4 key购买 nike

我的作品涉及 python 代码中的代码片段检测。因此,在我的工作中,我将用 python 编写一个脚本,这样我就可以将另一个 python 文件作为输入,并使用我的脚本在所需的位置插入任何必要的代码。

以下代码是我要检测的文件的示例代码:

A.py #normal un-instrumented code

statements
....
....

def move(self,a):
statements
......
print "My function is defined"
......

statements
......

我的脚本实际做的是检查 A.py 中的每一行,如果有“def”,则在 def 函数的代码之上插入一个代码片段

以下示例是最终输出的样子:

A.py #instrumented code

statements
....
....

@decorator #<------ inserted code
def move(self,a):
statements
......
print "My function is defined"
......

statements
......

但是我得到了不同的输出。以下代码是我得到的最终输出:

A.py #检测代码

statements
....
....

@decorator #<------ inserted code
def move(self,a):
statements
......
@decorator #<------ inserted code [this should not occur]
print "My function is defined"
......

statements
......

我可以理解,在检测的代码中,它识别“定义”一词中的“def”,因此它检测了上面的 a 代码。

实际上,检测的代码有很多这样的问题,我无法正确检测给定的 python 文件。还有其他方法可以区分实际的“def”和字符串吗?

谢谢

最佳答案

使用ast module正确解析文件。

此代码打印每个 def 语句的行号和列偏移量:

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

关于python - python中如何区分 "a string"和 "a actual code"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16809248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com