3

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

fields = ('name', 'description', 'long_description', 'foot_description')
a = 1
dict( (field, a) for field in fields)

当我从 python shell 运行它时,它给了我正确的字典。但是当我从 django shell 运行它时,我得到:

---------------------------------------------------------------------------
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

我的问题很简单:为什么?

4

1 回答 1

2

这似乎是一个已知问题并已在 Django 1.6 中修复

目前,票证中有建议的解决方法。“抓住以下几行(从这里https://github.com/django/django/blob/master/django/core/management/commands/shell.py)并用这个替换当前的实现(...):

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

您也可以python manage.py shell --plain从对同一张票的评论中尝试。

于 2013-08-06T12:35:16.260 回答