全局变量在Django shell中不起作用

时间:2013-06-01 02:23:28

标签: django shell global-variables

今天,当我在“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?

1 个答案:

答案 0 :(得分: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
相关问题