【发布时间】:2022-06-16 16:49:09
【问题描述】:
我试图将函数中的值存储到全局变量中,但它不起作用。这是我的代码:
API_TOKEN = ""
def read_config_file():
with open(config_path) as fileWithCredentials:
creds = yaml.safe_load(fileWithCredentials)
API_TOKEN = creds["cred"]["token"]
print(API_TOKEN) #This works
if __name__ == "__main__":
read_config_file()
print(API_TOKEN) #This doesnt work
如果我在 read_config_file 函数中打印 API_TOKEN 就可以了。但是,如果我想在主函数中打印它,变量是空的。谁能解释一下,问题出在哪里?
【问题讨论】:
-
函数开头缺少
global API_TOKEN