python - 如何从文件中解析 Python 模块

标签 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 解析它——公开它的类和方法。

最佳答案

您需要调用read。所以你的线

t = ast.parse(r.read)

应该是

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

参见 here有关文件的信息和 here有关 ast.parse 的信息

关于python - 如何从文件中解析 Python 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15518820/

相关文章:

python - 从 python 或 bash 批量填写 PDF 表单

java - 从路径中检索上一级目录名称

java - 解析java中可能是JSONObject或JSONArray的json字段

c++ - 解析 C++ 以对代码进行一些更改

ios - Swift中JSON解析返回数据

python - Jupyter Notebook/Pandas 目录

python - 从 PyQt 事件循环中执行 Python 代码

python - 如何使用简单的预卸载脚本扩展 distutils?

python - 创建 Python RPM

html - 如何使用 Ruby 解析 HTML 文件标题