ast.parse的filename参数有什么用?

时间:2013-07-10 13:20:29

标签: python abstract-syntax-tree

文档内容如下:

ast.parse(source, filename='<unknown>', mode='exec')

    Equivalent to compile(source, filename, mode, ast.PyCF_ONLY_AST).


compile(source, filename, mode[, flags[, dont_inherit]])

    The filename argument should give the file from which the code was read;
    pass some recognizable value if it wasn’t read from a file
    ('<string>' is commonly used).

但它并没有告诉我如何从AST节点返回这个文件名。或者如何使用此文件名参数。它只是一个存根吗?

1 个答案:

答案 0 :(得分:3)

它在代码对象上设置co_filename属性,该属性用于在回溯中显示文件名。除此之外,你传递的价值并不重要。

>>> c = compile('raise Exception("spam")', 'eggs', 'exec')
>>> eval(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "eggs", line 1, in <module>
Exception: spam