如何从文件中解析Python模块

时间:2013-03-20 08:43:46

标签: python parsing

我看到this SO question并尝试使用它创建一个包含2种方法的.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 个答案:

答案 0 :(得分:8)

您需要致电read。你的行

t = ast.parse(r.read)

应该是

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

有关文件的信息,请参阅here;有关ast.parse的信息,请参阅here

答案 1 :(得分:4)

使用:

t = ast.parse(r.read()) # () is needed

来源:http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

答案 2 :(得分:2)

您正在尝试解析文件中读取的函数。

你想要

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

或(更接近于示例)

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

t = ast.parse(r.read)

答案 3 :(得分:2)

如果您想动态公开您的类和方法,那么您可能需要使用evalcompile

在这种情况下,您可以执行以下操作。

创建文件:

#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可能不是那么好的选择,但我不知道其他方式。我很高兴看到其他解决方案