如何区分“字符串"和“实际代码"在python中? [英] How to differentiate between "a string" and "a actual code" in python?

查看:122
本文介绍了如何区分“字符串"和“实际代码"在python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My works relates to instrumentation of code fragments in python code. So in my work i would be writing a script in python such that I take another python file as input and insert any necessary code in the required place with my script.

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

The following code is a sample code of a file which i would be instrumenting:

A.py #normal un-instrumented code

statements
....
....

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

statements 
......

我的脚本的实际作用是检查A.py中的每一行,如果有"def",则在def函数的代码上方插入代码片段

My script what actually does is to check each lines in the A.py and if there is a "def" then a code fragment is instrumented on top of the code the def function

以下示例是最终输出的方式:

The following example is how the final out put should be:

A.py #instrumented code

statements
....
....

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

statements 
......

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

But I have been resulted with different output. The following code is the final output which i am getting:

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",因此它可以检测其上方的代码.

I can understand that in the instrumented code it recognizes "def" in the word "defined" and so it instruments the a code above it.

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

In realty the instrumented code has lots of these problems I was not able to properly instrument the given python file. Is there any other way to differentiate the actual "def" from string?

谢谢

推荐答案

使用 模块以正确解析文件.

此代码显示每个def语句的行号和列偏移:

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

这篇关于如何区分“字符串"和“实际代码"在python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆