正確初始化導入模塊我有一個文件test.py
:可以用Python
import logging
def func():
logger.info('some info')
if __name__ == '__main__':
logger = logging.getLogger()
func()
其中運行良好。當我從另一個文件中測試導入func並調用func()
方法時,它會給我帶來global name 'logger' is not defined
錯誤。
from test import func
def another_fun():
func()
即使我把another_func()
logger = logging.getLogger()
調用func()
之前,它仍然給了我這樣的錯誤。我想知道在這種情況下,通過適當的初始化從其他文件導入函數的標準方式是什麼。非常感謝。
我認爲'func()'不能識別'logger'作爲一個全局變量,因爲你沒有告訴它這麼做。你有沒有嘗試之前添加一個'全球記錄器'行?看看這個:http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them – tomasyany
這是因爲你定義'記錄器'在'main'部分,所以它永遠不會被導入。 –