2009-03-03 72 views
1

我有兩個文件,一個在webroot中,另一個是位於Web根目錄之上的一個文件夾的引導程序(這是CGI編程順便一提)。由外部模塊分配的Python變量可供打印,但不能在目標模塊中分配

Web根目錄中的索引文件導入引導併爲其分配一個變量,然後調用一個函數來初始化應用程序。到此爲止的一切都按預期工作。

現在,在引導程序文件中我可以打印變量,但是當我嘗試爲該變量賦值時會拋出一個錯誤。如果拿走賦值語句,則不會引發錯誤。

我真的很好奇在這種情況下範圍的工作原理。我可以打印這個變量,但我不能贊成。這是關於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> 
+0

可能會幫助發佈您的錯誤消息。 – monkut 2009-03-03 07:10:58

+0

您的縮進顯示在您的bootstrap.py列表中。 – monkut 2009-03-03 07:12:31

+0

謝謝你的提醒,我會編輯帖子。 – BlueBadger 2009-03-03 10:02:19

回答

3

試試這個:

 

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

沒有 '全球VAR' 蟒蛇要使用局部變量VAR,給你「UnboundLocalError:引用局部變量 'VAR'在分配之前「

0

不要聲明它是全局的,而是傳遞它,並返回它,如果你需要一個新的值,像這樣:

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

---- 

import bootstrap 
b = bootstrap.initialize('testVar')