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

Why is `exec()` not working in a script but working interactively?

我正在将凭据文件读入字符串,然后在该字符串上 运行 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)

您需要将 globals()(可能还有 locals())集合传递给 exec():

exec(credentials, globals())

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