【问题标题】:Global variables don't works in Django shell全局变量在 Django shell 中不起作用
【发布时间】:2013-06-01 02:23:28
【问题描述】:

今天,当我在“python manage.py shell”中进行一些测试时,无法引用全局变量,请参阅:


In [9]: import subprocess as s

In [10]: def test():
    global s
    f = s.check_output('ls /tmp', shell=True)
    return f
   ....: 

In [11]: test()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 test()

/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in test()
      1 def test():
      2     global s
----> 3     f = s.check_output('ls /tmp', shell=True)
      4     return f

**NameError: global name 's' is not defined**

我尝试引用的每个全局变量都面临相同的错误。 但是将代码放在views.py中,它可以工作...... 我该如何修复 django shell?

【问题讨论】:

    标签: django shell global-variables


    【解决方案1】:

    我在 python 2.6 和 django 1.3 中尝试了与您的代码等效的代码,它运行良好。不建议你downrev,但至少这可能是一个线索。此外,如果您只是使用 s,那么您不需要在函数中进行全局声明。我认为只有在修改 s 时才需要它。

    In [60]: import subprocess as s
    
    In [61]: def test():
        global s
        f = s.check_call('ls /tmp', shell=True)
        return f
       ....:
    
    In [65]: test()
    Out[65]: 0
    

    【讨论】:

    • 好的,我可以在没有 ipython 的情况下使用 django shell:./manage.py shell --plain [link]stackoverflow.com/questions/2078059/… 但是重新安装 django 和 ipython 都不能解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2017-05-20
    • 2013-09-21
    • 1970-01-01
    相关资源
    最近更新 更多