由外部模块分配的Python变量可以进行打印,但不能在目标模块中进行分配

StackOverflow https://stackoverflow.com/questions/605399

  •  03-07-2019
  •  | 
  •  

我有两个文件,一个在webroot中,另一个是一个bootstrap,位于web根目录上方的一个文件夹(顺便说一下,这是CGI编程)。

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

现在,在bootstrap文件中我可以打印变量,但是当我尝试为变量赋值时,会抛出错误。如果你拿走赋值语句就不会抛出任何错误。

我真的很好奇在这种情况下范围如何运作。我可以打印变量,但我无法对其进行操作。这是在Python 3上。

<强> index.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()

<强> bootstrap.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>
有帮助吗?

解决方案

试试这个:


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

没有'global VAR'python想要使用局部变量VAR并给你“UnboundLocalError:局部变量'VAR'在赋值之前引用”

其他提示

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

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

----

import bootstrap
b = bootstrap.initialize('testVar')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top