开发者

Getting module name with ast

How to get a python module name using ast? I tried the following to get the Module Node, but looks like it does not have the name information:

class v(ast.NodeVisitor):
    def visit_Module(self, node):
        print 开发者_Python百科"Module : %s" % node

v().visit_Module(ast.parse(f.read(), filename))

I basically need the actual module name (If it is inside a package then the complete one like a.b.module).


AFAIU, this information doesn't exist in ast. More formally, the abstract grammar for Module in Python is:

mod = Module(stmt* body)
    | Interactive(stmt* body)
    | Expression(expr body)

    -- not really an actual node but useful in Jython's typesystem.
    | Suite(stmt* body)

So as you can see a Module just has a body which is a list of statement nodes. There's no name.

Do note that you pass f.read() to the visitor. That returns the contents of the file, without actually knowing or caring how that file is named - where can you take the module name from it?

From executing Python code, you can use __name__ and __package__ from inside Python code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜