外部モジュールによって割り当てられたPython変数は、印刷用にアクセスできますが、ターゲットモジュール内の割り当てにはアクセスできません
質問
2つのファイルがあります。1つはwebrootにあり、もう1つはwebルート上の1つのフォルダーにあるブートストラップです(これはCGIプログラミングです)。
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>
解決
これを試してください:
def initialize():
global VAR
print('Content-type: text/html\n\n')
print(VAR)
VAR = 'h'
print(VAR)
「グローバル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')
所属していません StackOverflow