作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的作品涉及 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/
我是一名优秀的程序员,十分优秀!