这很奇怪。我在 PyDev 中运行这个程序
import ast
import sys
if __name__ == '__main__':
print sys.version
src = '''
print 3*4+5**2
'''
print dir(ast)
n = ast.parse(src)
print n
Run Code Online (Sandbox Code Playgroud)
它输出:
2.7.5 |Anaconda 1.6.0 (64-bit)| (default, May 31 2013, 10:45:37) [MSC v.1500 64 bit (AMD64)]
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
Traceback (most recent call last):
File ["C:\research\ast\ast\test1.py", line 16, in <module>
n = ast.parse(src)
AttributeError: 'module' object has no attribute 'parse'
Run Code Online (Sandbox Code Playgroud)
但是当我在 cmdline 中运行它时,它会打印以下内容:
C:\research\ast\ast>python test1.py
2.7.5 |Anaconda 1.6.0 (64-bit)| (default, May 31 2013, 10:45:37) [MSC v.1500 64
bit (AMD64)]
['AST', 'Add', 'And', 'Assert', 'Assign', 'Attribute', 'AugAssign', 'AugLoad', '
AugStore', 'BinOp', 'BitAnd', 'BitOr', 'BitXor', 'BoolOp', 'Break', 'Call', 'Cla
ssDef', 'Compare', 'Continue', 'Del', 'Delete', 'Dict', 'DictComp', 'Div', 'Elli
psis', 'Eq', 'ExceptHandler', 'Exec', 'Expr', 'Expression', 'ExtSlice', 'FloorDi
v', 'For', 'FunctionDef', 'GeneratorExp', 'Global', 'Gt', 'GtE', 'If', 'IfExp',
'Import', 'ImportFrom', 'In', 'Index', 'Interactive', 'Invert', 'Is', 'IsNot', '
LShift', 'Lambda', 'List', 'ListComp', 'Load', 'Lt', 'LtE', 'Mod', 'Module', 'Mu
lt', 'Name', 'NodeTransformer', 'NodeVisitor', 'Not', 'NotEq', 'NotIn', 'Num', '
Or', 'Param', 'Pass', 'Pow', 'Print', 'PyCF_ONLY_AST', 'RShift', 'Raise', 'Repr'
, 'Return', 'Set', 'SetComp', 'Slice', 'Store', 'Str', 'Sub', 'Subscript', 'Suit
e', 'TryExcept', 'TryFinally', 'Tuple', 'UAdd', 'USub', 'UnaryOp', 'While', 'Wit
h', 'Yield', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '
__version__', 'alias', 'arguments', 'boolop', 'cmpop', 'comprehension', 'copy_lo
cation', 'dump', 'excepthandler', 'expr', 'expr_context', 'fix_missing_locations
', 'get_docstring', 'increment_lineno', 'iter_child_nodes', 'iter_fields', 'keyw
ord', 'literal_eval', 'mod', 'operator', 'parse', 'slice', 'stmt', 'unaryop', 'w
alk']
<_ast.Module object at 0x0000000002A99EB8>
Run Code Online (Sandbox Code Playgroud)
可能出了什么问题?
看来ast你在PyDev中导入的不是标准库中的ast模块,而是一个包。
我猜:
__init__.py在与你的 test1.py 相同的目录中有一个文件。
您在项目创建过程中选择了“将项目目录添加到 PYTHONPATH”。
这两者结合起来就会导致该错误。标准库中的 ast 模块被该ast包隐藏。
在cmdline python中,该ast包不在搜索路径中,因此导入了ast模块。
如果将 test1.py 更改为
import ast
if __name__ == '__main__':
print ast.__file__
Run Code Online (Sandbox Code Playgroud)
我猜 PyDev 中的输出是
C:\research\ast\ast\__init__.pyc
Run Code Online (Sandbox Code Playgroud)