繁体   English   中英

如何在python中区分“字符串”和“实际代码”?

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

我的作品涉及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 
......

我可以理解,在已检测的代码中,它可以识别单词“ defined”中的“ def”,因此可以检测其上方的代码。

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

谢谢

使用ast模块正确解析文件。

此代码显示每个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

您可以使用正则表达式。 为了避免在引号中使用def ,那么您可以使用否定环顾:

import re

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

    print line 

但是,可能还有其他一些您可能无法想到的def发生,并且如果我们不小心的话,最终将重新编写Python解析器。 从长远来看,@ Janne Karila建议使用ast.parse可能更安全。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM