简体   繁体   English

如何从文件中解析Python模块

[英]How to parse a Python module from file

I saw this SO question and tried using it by creating a .py file with 2 methods and trying to read it. 我看到了这个问题并尝试使用它创建一个包含2种方法的.py文件并尝试阅读它。
The file: 文件:

def f1(a):
    print "hello", a
    return 1

def f2(a,b):
    print "hello",a,", hello",b

Trying to read it: 试着读它:

>>> r = open('ToParse.py','r')
>>> t = ast.parse(r.read)

Exception thrown: 抛出异常:

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

What am I doing wrong? 我究竟做错了什么?
My goal is to get a python module and be able to parse it using Python - expose its classes and methods. 我的目标是获得一个python模块并能够使用Python解析它 - 公开它的类和方法。

You need to call read . 你需要打电话给read So your line 所以你的路线

t = ast.parse(r.read)

Should be 应该

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

See here for info on files and here for info on ast.parse 这里为上的文件信息,并在这里对ast.parse信息

If you want to expose your classes and methods dynamically, then you probably need to use eval along with compile . 如果要动态公开类和方法,则可能需要使用evalcompile

In this case you may do it like the following. 在这种情况下,您可以像下面这样做。

Create a file: 创建一个文件:

#test.py
def hello():
    print "hello"

And you can call it like this: 你可以这样称呼它:

#main.py
testContent = open("test.py").read()
#evaluate a content
eval(compile(testContent, "<string>", 'exec'))
#call function
hello() #prints hello

EDIT : there is another way to evaluate file: 编辑 :还有另一种评估文件的方法:

#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

I do realize, that eval may be not that good choice, but I don't know other way. 我确实意识到, eval可能不是一个好的选择,但我不知道其他方式。 I'd glad to see other solution 我很高兴看到其他解决方案

You are trying to parse the function read on the file. 您正在尝试解析文件上读取的函数。

You want 你要

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

or (to more closely follow the example) 或(更密切地遵循这个例子)

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

not

t = ast.parse(r.read)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM