Getting callfunc from ast code.

G

Glich

"""Hi, how can I extend the code shown below so that I can identify
any "CallFunc" in "func.code" and identify the value of "node" in
"CallFunc"? Thanks.

This is my code so far:
"""

""" Given a python file, this program prints out each function's name
in that file, the line number and the ast code of that function.

"""

import compiler
import compiler.ast

parse_file = compiler.parseFile("/home/glich/file.py")

count = 0

while count < (len(parse_file.node.nodes) - 1):

func = parse_file.node.nodes[count]

print "\nFunc name: " + str(func.name)
print "Func line number: " + str(func.lineno) + "\n"

print str(func.code) + "\n"

count += 1


"""file.py:


def fun1():

print "Hi"
hi = "1"

fun2()
fun4()

def fun2():

fun3()

def fun3():

fun4()

def fun4():
print "Hi"

fun1()

"""
 
P

Paul Boddie

"""Hi, how can I extend the code shown below so that I can identify
any "CallFunc" in "func.code" and identify the value of "node" in
"CallFunc"? Thanks.

This is my code so far:
"""

I tend to use isinstance to work out what kind of AST node I'm looking
at, although I often use the visitor infrastructure to avoid doing
even that.
""" Given a python file, this program prints out each function's name
in that file, the line number and the ast code of that function.

"""

import compiler
import compiler.ast

parse_file = compiler.parseFile("/home/glich/file.py")

count = 0

while count < (len(parse_file.node.nodes) - 1):

func = parse_file.node.nodes[count]

A quick style tip here: it's easier to iterate over the nodes, and if
you want a counter, use the enumerate built-in function. Together with
the above advice...

for count, func in enumerate(parse_file.node.nodes):
if isinstance(func, compiler.ast.CallFunc):
...
print "\nFunc name: " + str(func.name)
print "Func line number: " + str(func.lineno) + "\n"

print str(func.code) + "\n"

Take a look at the help text for enumerate to see how I arrived at the
above:

help(enumerate)

Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,144
Latest member
KetoBaseReviews
Top