【问题标题】:Value does not store to global variable in Python [duplicate]值不会存储到 Python 中的全局变量 [重复]
【发布时间】: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

标签: python global-variables


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 1970-01-01
  • 2021-08-02
  • 2014-01-14
  • 2015-08-19
  • 1970-01-01
相关资源
最近更新 更多