2013-08-02 61 views
3

我有问题,与Django外壳的奇怪行为。我有这样的代码:内联django外壳与python外壳的变量范围

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

当我从蟒蛇运行壳它给我正确的字典。但是当我从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 

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

+1

似乎无法将其复制到我的外壳上。 :/ –

+0

我可以在Django 1.3 IPython shell中复制这个错误。 – aychedee

+0

@aychedee我不能......'Out [3]:{'description':1,'foot_description':1,'long_description':1,'name':1}' –

回答

2

它似乎是a known issue and fixed in 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,从同一票评论。