python - django的shell下访问任何对象都出现错误?

 真真贱贱_474 发布于 2022-11-05 01:55

开发环境是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本身是正常的。

2 个回答
  • 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。没意义的。

    2022-11-12 01:45 回答
  • 补充一下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
    
    2022-11-12 01:45 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有