我看到了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
解析它——公开它的类和方法。
最佳答案
您需要调用read
。所以你的线
t = ast.parse(r.read)
应该是
t = ast.parse(r.read())
关于python - 如何从文件中解析 Python 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15518820/