How to parse a Python module from file
parsing, python
Solution
If you want to expose your classes and methods dynamically, then you probably need to use eval along with compile.
In this case you may do it like the following.
Create a file:
#test.py
def hello():
print "hello"
And you can call it like this:
#main.py
testContent = open("test.py").read()
#evaluate a content
eval(compile(testContent, "<string>", 'exec'))
#call function
hello() #prints hello
EDIT: there is another way to evaluate file:
#main.py
#evaluate a content
eval(compile("import test", "<string>", 'exec')) #test.py
#check list of methods
dir(test) # ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello']
#call function
hello() #prints hello
I do realize, that `eval` may be not that good choice, but I don't know other way. I'd glad to see other solution
Problem
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.