1

我有两个文件,一个在 webroot 中,另一个是位于 web root 上方一个文件夹的引导程序(顺便说一下,这是 CGI 编程)。

Web 根目录中的索引文件导入引导程序并为其分配一个变量,然后调用 aa 函数来初始化应用程序。到目前为止,一切都按预期工作。

现在,在引导文件中,我可以打印变量,但是当我尝试为变量赋值时,会引发错误。如果您拿走赋值语句,则不会引发错误。

我真的很好奇范围界定在这种情况下是如何工作的。我可以打印变量,但我不能分配给它。这是在 Python 3 上。

索引.py

# Import modules
import sys
import cgitb;

# Enable error reporting
cgitb.enable()
#cgitb.enable(display=0, logdir="/tmp")

# Add the application root to the include path
sys.path.append('path')

# Include the bootstrap
import bootstrap

bootstrap.VAR = 'testVar'

bootstrap.initialize()

引导程序.py

def initialize():
    print('Content-type: text/html\n\n')
    print(VAR)
    VAR = 'h'
    print(VAR)

谢谢。

编辑:错误信息

UnboundLocalError: local variable 'VAR' referenced before assignment 
      args = ("local variable 'VAR' referenced before assignment",) 
      with_traceback = <built-in method with_traceback of UnboundLocalError object at 0x00C6ACC0>
4

2 回答 2

3

试试这个:


def initialize():
    global VAR
    print('Content-type: text/html\n\n')
    print(VAR)
    VAR = 'h'
    print(VAR)

如果没有“全局 VAR”,python 想要使用局部变量 VAR 并为您提供“UnboundLocalError:分配前引用的局部变量 'VAR'”

于 2009-03-03T07:23:30.337 回答
0

不要将它声明为全局,而是传递它并在需要新值时返回它,如下所示:

def initialize(a):
    print('Content-type: text/html\n\n')
    print a
    return 'h'

----

import bootstrap
b = bootstrap.initialize('testVar')
于 2009-03-03T12:15:47.293 回答