Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a Python module from file

Tags:

python

parsing

I saw this SO question and tried using it by creating a .py file with 2 methods and trying to read it.
The file:

def f1(a):
    print "hello", a
    return 1

def f2(a,b):
    print "hello",a,", hello",b

Trying to read it:

>>> r = open('ToParse.py','r')
>>> t = ast.parse(r.read)

Exception thrown:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python26\lib\ast.py", line 37, in parse
    return compile(expr, filename, mode, PyCF_ONLY_AST)
TypeError: expected a readable buffer object

What am I doing wrong?
My goal is to get a python module and be able to parse it using Python - expose its classes and methods.

like image 840
Noich Avatar asked Mar 20 '13 08:03

Noich


People also ask

What is parse module in Python?

The parser module provides an interface to Python's internal parser and byte-code compiler. The primary purpose for this interface is to allow Python code to edit the parse tree of a Python expression and create executable code from this.

What is parsing in Python example?

What is Parsing? Parsing is defined as the process of converting codes to machine language to analyze the correct syntax of the code. Python provides a library called a parser.

What is file parsing?

The File Parser process enables you to convert data from an external file into PeopleSoft data and place it into tables in your Campus Solutions database. The external file can be a delimited file or a flat file. It can be a simple file with one row type or a complex file with several row types.


1 Answers

You need to call read. So your line

t = ast.parse(r.read)

Should be

t = ast.parse(r.read())

See here for info on files and here for info on ast.parse

like image 76
pradyunsg Avatar answered Oct 21 '22 04:10

pradyunsg