为什么我的代码可以从交互式shell运行,但是从文件运行时却不行?

时间:2012-03-11 22:37:00

标签: python python-module pprint python-interactive

我正在尝试使用pprint模块检查Python中的一些变量,我很高兴使用交互式shell和下面的代码:

import pprint
pp = pprint.PrettyPrinter()
stuff = ['cakes','bread','mead']
pp.pprint(stuff)

但是,当我将上述内容放入pprint.py并使用python pprint.py运行时,我收到错误:

$ python dev/pars/pprint.py 
Traceback (most recent call last):
  File "dev/pars/pprint.py", line 1, in ?
    import pprint
  File "/home/origina2/dev/pars/pprint.py", line 2, in ?
    pp = pprint.PrettyPrinter()
AttributeError: 'module' object has no attribute 'PrettyPrinter'

与交互式shell相比,从文件运行Python代码时调用模块的方式有何不同?

1 个答案:

答案 0 :(得分:9)

您将程序命名为pprint.py,因此在import pprint行尝试导入自己。它成功了,但你的 pprint.py不包含所谓的PrettyPrinter。

更改您的代码名称。 [并且,要清楚,删除任何pprint.pyc或pprint.pyo文件..]