python - django的shell下访问任何对象都出现错误?
ringa_lee
ringa_lee 2017-04-17 11:45:26
[Python讨论组]

开发环境是PYTHON3.3+DJANGO1.6 启动django shell后,导入是可用的,但是访问任何对象都提示:

AttributeError: 'dict' object has no attribute '_'

我一开始还以为是我的工程下的模块有问题,后来随便输入1,也出现这个问题了。

>>> 1
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home2/myhome/.pythonrc.py", line 94, in my_displayhook
    __builtins__._ = value
AttributeError: 'dict' object has no attribute '_'

这个是django shell的启动有问题吗?python3本身是正常的。

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
阿神

补充一下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
阿神

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。没意义的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号