代码之家  ›  专栏  ›  技术社区  ›  BlandCorporation

为什么“exec()”不是在脚本中工作,而是以交互方式工作?

  •  2
  • BlandCorporation  · 技术社区  · 7 年前

    我在一个凭证文件中读取一个字符串,然后运行 exec() 在该字符串上,使各种凭据作为变量可用。凭据文件包含以下文本:

    customer_number = "9999999999"
    PIN             = "9999999999"
    passcode        = "9999999999"
    account_code    = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    

    这在交互式Python中有效(变量可用),但在脚本中失败。为什么会这样?我怎样才能让它工作?

    with open(filepath_credentials, "r") as file_credentials:
        credentials = file_credentials.read()
        exec(credentials)
    print(customer_number)
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Greg Hewgill    7 年前

    你需要通过 globals() (也可能是 locals() )收集到 exec()

    exec(credentials, globals())
    

    这允许 exec() 修改脚本的全局变量。Python交互式解释器在这里的工作方式略有不同。