内联django shell与python shell中的变量范围

内联django shell与python shell中的变量范围,python,django,django-shell,Python,Django,Django Shell,我有个问题,django shell的奇怪行为。我有以下代码: fields = ('name', 'description', 'long_description', 'foot_description') a = 1 dict( (field, a) for field in fields) 当我从pythonshell运行它时,它是正确的dict。但是当我从djangoshell运行它时,我得到: ---------------------------------------------

我有个问题,django shell的奇怪行为。我有以下代码:

fields = ('name', 'description', 'long_description', 'foot_description')
a = 1
dict( (field, a) for field in fields)
当我从pythonshell运行它时,它是正确的dict。但是当我从djangoshell运行它时,我得到:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in     <module>()
----> 1 dict( (field, a) for field in fields)

/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in    <genexpr>((field,))
----> 1 dict( (field, a) for field in fields)

NameError: global name 'a' is not defined
---------------------------------------------------------------------------
NameError回溯(最近一次呼叫上次)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in()
---->1个dict((字段,a)表示字段中的字段)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in((字段,)
---->1个dict((字段,a)表示字段中的字段)
NameError:未定义全局名称“a”
我的问题很简单:为什么?似乎是这样

目前,有一个建议的解决办法。“获取以下行(从这里开始)并将当前实现(…)替换为以下内容:”

def ipython(自):
尝试:
从IPython.frontend.terminal.ipapp导入TerminalIPythonApp
app=TerminalIPythonApp.instance()
app.initialize(argv=[])
app.start()
除恐怖外:
#IPython<0.11
#显式地将空列表作为参数传递,因为
#IPython将使用此脚本中的sys.argv。
尝试:
从IPython.Shell导入IPShell
shell=IPShell(argv=[])
shell.mainloop()
除恐怖外:
#IPython根本找不到,提高警惕
提升

您还可以从同一票据上的注释中尝试
python manage.py shell--plain

似乎无法在我的shell上复制此功能:/我可以在Django 1.3 IPython shell中复制此错误。@aychedee我不能<代码>输出[3]:{'description':1,'foot_description':1,'long_description':1,'name':1}@OP:您使用的是什么版本?我不能在Django 1.5上复制它。我可以在Django 1.4.1 IPython shell和Django IPython shell 1.3.7上复制它。
def ipython(self):
    try:
        from IPython.frontend.terminal.ipapp import TerminalIPythonApp
        app = TerminalIPythonApp.instance()
        app.initialize(argv=[])
        app.start()
    except ImportError:
        # IPython < 0.11
        # Explicitly pass an empty list as arguments, because otherwise
        # IPython would use sys.argv from this script.
        try:
            from IPython.Shell import IPShell
            shell = IPShell(argv=[])
            shell.mainloop()
        except ImportError:
            # IPython not found at all, raise ImportError
            raise