7

我看到了这个 SO question并尝试通过使用.py2 种方法创建一个文件并尝试读取它来使用它。
文件:

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 回答 4

8

你需要打电话read。所以你的线

t = ast.parse(r.read)

应该

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

有关文件的信息,请参见此处,有关 ast.parse 的信息请参见此处

于 2013-03-20T08:59:03.297 回答
4

采用:

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

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

于 2013-03-20T08:52:31.537 回答
4

如果你想动态地公开你的类和方法,那么你可能需要使用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可能不是那么好的选择,但我不知道其他方式。我很高兴看到其他解决方案

于 2013-03-20T09:00:57.250 回答
2

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

你要

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

或(更紧密地遵循示例)

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

不是

t = ast.parse(r.read)
于 2013-03-20T08:58:19.723 回答