不用担心 :) 欢迎使用 Python!它抛出这个错误是因为它正在寻找一个不存在的全局变量——它不存在的原因是因为你没有达到if type == "accounts" 条件!
试试这个:
for i in included:
global signs,accounts, regions
global sign_name, acc_name, rg_name
regions = "no region yet"
acc_name = "no acc_name yet"
if type == "regions"
regions = i
rg_name = regions['data']['region']
if type == "accounts"
accounts = i
acc_name = accounts['data']['account']
print("Stopping account " + acc_name + " in region " + rg_name)
这将清除错误并至少让您看到可能出现的其他错误:)
我还要指出,我相信您会从其他人那里听到,您没有理由在这种情况下声明全局变量。它最初是说“找不到全局变量”,因为在你输入 global 关键字之前,它没有触发 if 语句,所以首先它检查了 locals() 变量,但没有找到它,搜索了 globals() 变量,但没有发现它被踢出错误。
您可以删除 global 变量,它会像这样正常工作:
for i in included:
regions = "no region yet"
acc_name = "no acc_name yet"
if type == "regions"
regions = i
rg_name = regions['data']['region']
if type == "accounts"
accounts = i
acc_name = accounts['data']['account']
print("Stopping account " + acc_name + " in region " + rg_name)
另一个快速说明,永远不要将type 作为变量...改用type_。原因是type 是一个builtin Python 函数,如果您使用type 作为变量,您会不小心为该内置名称起别名。
最后,稍微清理一下脚本:
# only use "i" when you're using numbers, otherwise just call it
# the name of the data you're using :)
for account_data in included:
regions = "no region yet"
acc_name = "no acc_name yet"
if type_ == "regions"
rg_name = account_data['data']['region']
if type_ == "accounts"
acc_name = account_data['data']['account']
# here's an example of Pythonic string formatting :)
print("Stopping account {} in region {}".format(acc_name, rg_name))