How to get source corresponding to a Python AST node?

前端 未结 3 1057
一生所求
一生所求 2020-12-15 22:22

Python AST nodes have lineno and col_offset attributes, which indicate the beginning of respective code range. Is there an easy way to get also the

3条回答
  •  天命终不由人
    2020-12-15 23:13

    Hi I know its very late , But I think is this is what you are looking for, I am doing the parsing only for function definitions in the module. We can get the first and last line of the ast node by this method. This way the source code lines of a function definition can be obtained by parsing the source file by reading only the lines we need . This is a very simple example ,

    st='def foo():\n    print "hello" \n\ndef bla():\n    a = 1\n    b = 2\n  
    c= a+b\n    print c'
    
    import ast 
    tree = ast.parse(st)
    for function in tree.body:
        if isinstance(function,ast.FunctionDef):
            # Just in case if there are loops in the definition
            lastBody = func.body[-1]
            while isinstance (lastBody,(ast.For,ast.While,ast.If)):
                lastBody = lastBody.Body[-1]
            lastLine = lastBody.lineno
            print "Name of the function is ",function.name
            print "firstLine of the function is ",function.lineno
            print "LastLine of the function is ",lastLine
            print "the source lines are "
            if isinstance(st,str):
                st = st.split("\n")
            for i , line in enumerate(st,1):
                if i in range(function.lineno,lastLine+1):
                    print line
    

提交回复
热议问题