开发环境是PYTHON3.3+DJANGO1.6 启动django shell后,导入是可用的,但是访问任何对象都提示:
AttributeError: 'dict' object has no attribute '_'
我一开始还以为是我的工程下的模块有问题,后来随便输入1,也出现这个问题了。
>>> 1 Traceback (most recent call last): File "", line 1, in File "/home2/myhome/.pythonrc.py", line 94, in my_displayhook __builtins__._ = value AttributeError: 'dict' object has no attribute '_'
这个是django shell的启动有问题吗?python3本身是正常的。
Python 3 只有 builtins
模块,没有 __builtin__
了。至于 __builtins__
变量:
As an implementation detail, most modules have the name
__builtins__
made available as part of their globals. The value of__builtins__
is normally either this module or the value of this module's__dict__
attribute. Since this is an implementation detail, it may not be used by alternate implementations of Python.
所以,不要用它。_
变量应该由 shell 的实现来处理的,不要在 displayhook 里处理。Python 自身的 shell 是使用 builtins 命名空间的,但是 code 模块使用的是全局空间。
另外,你也没必要反复 import 和删掉 pprint。没意义的。
补充一下pythonrc.py抛出异常部分的代码:
import sys # Enable Color Prompts sys.ps1 = '%s>>> %s' % (_c['Green'], _c['Normal']) sys.ps2 = '%s... %s' % (_c['Red'], _c['Normal']) # Enable Pretty Printing for stdout def my_displayhook(value): if value is not None: try: import __builtin__ __builtin__._ = value except ImportError: __builtins__._ = value import pprint pprint.pprint(value) del pprint sys.displayhook = my_displayhook