Variables scope in inline django shell, vs python shell

纵饮孤独 提交于 2019-12-22 10:04:14

问题


I have problem, with strange behavior of django shell. I have this code:

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

When I run it from python shell it's give me right dict. But when i running it from django shell i get:

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

My question is simple: WHY?


回答1:


It seems to be a known issue and fixed in Django 1.6.

For the time being, there is a suggested workaround in the ticket. "Grab the following lines (from here https://github.com/django/django/blob/master/django/core/management/commands/shell.py) and replace the current implementation (...) with this":

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

You can also try python manage.py shell --plain, from a comment on the same ticket.



来源:https://stackoverflow.com/questions/18014728/variables-scope-in-inline-django-shell-vs-python-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!