بيثون تعيين متغير خارجي وحدة يمكن الوصول إليها في الطباعة ولكن لا تعيين في وحدة الهدف

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

  •  03-07-2019
  •  | 
  •  

سؤال

لدي ملفين واحد في webroot آخر هو التمهيد يقع مجلد واحد فوق ويب الجذر (هذا هو CGI البرمجة بالمناسبة).

مؤشر الملف في جذر ويب الواردات التمهيد و يعين متغير ، ثم يدعو وظيفة تهيئة التطبيق.كل شيء هنا يعمل كما هو متوقع.

الآن في ملف التمهيد يمكنني طباعة متغير, ولكن عند محاولة تعيين قيمة متغير خطأ يتم طرح.إذا كنت تأخذ بعيدا العبارة المهمة لا يتم طرح أخطاء.

أنا الغريب حقا حول كيفية تحديد النطاق يعمل في هذه الحالة.لا يمكن طباعة متغير, ولكن لا أستطيع asign إلى ذلك.هذا هو على بيثون 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)

دون 'العالمية فار python تريد استخدام متغير محلي فار و تعطيك "UnboundLocalError:المتغير المحلي فار 'المشار إليها قبل التنازل"

نصائح أخرى

لا يعلن العالمية ، تمريرها بدلا وإعادته إذا كنت بحاجة إلى قيمة جديدة, مثل هذا:

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