如何从文件解析Python模块
我看到这个StackOverflow的问题,于是我尝试创建一个包含两个方法的.py
文件,并试图读取它。
这个文件是:
def f1(a):
print "hello", a
return 1
def f2(a,b):
print "hello",a,", hello",b
我试着读取它:
>>> r = open('ToParse.py','r')
>>> t = ast.parse(r.read)
出现的异常:
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
我哪里做错了?
我的目标是获取一个python
模块,并能够使用Python
对其进行解析 - 也就是能够访问它的类和方法。
4 个回答
4
使用:
t = ast.parse(r.read()) # () is needed
来源:http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
6
如果你想动态地使用你的类和方法,那你可能需要用到 eval 和 compile。
在这种情况下,你可以这样做。
首先,创建一个文件:
#test.py
def hello():
print "hello"
然后你可以这样调用它:
#main.py
testContent = open("test.py").read()
#evaluate a content
eval(compile(testContent, "<string>", 'exec'))
#call function
hello() #prints hello
补充说明: 还有另一种方法可以执行文件:
#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
我知道,使用 eval
可能不是最好的选择,但我不知道其他方法。如果有其他解决方案,我很乐意看到。