【问题标题】:"errorMessage": "local variable 'action' referenced before assignment", "errorType": "UnboundLocalError"“errorMessage”:“分配前引用的局部变量'action'”,“errorType”:“UnboundLocalError”
【发布时间】:2020-01-18 09:00:40
【问题描述】:

我尝试将变量操作设为全局,但没有成功。似乎 else 语句中的任何变量都与其余代码隔离,尽管它们在 for 循环中位于同一代码块中。

for group in auto_scaling_groups:
    if servers_need_to_be_started(group):
        pass
    else:
        action = "Stopping"
        min_size = 0
        max_size = 0
        desired_capacity = 0

    print("Version is {}".format(botocore.__version__))

    print (action + ": " + group)  #Error in this line 
    response = client.update_auto_scaling_group(
        AutoScalingGroupName=group,
        MinSize=min_size,
        MaxSize=max_size,
        DesiredCapacity=desired_capacity,
    )

    print (response)

【问题讨论】:

    标签: python


    【解决方案1】:

    如果 servers_need_to_be_started(group) 为 True,则永远不会分配 var action

    在开始操作时设置一些默认值。

    【讨论】:

      【解决方案2】:

      错误是说“在执行 if 语句的“then”块后,action 未设置,但在错误行中使用”。解决方法是确保在执行 if 语句的“then”块时分配 actionmin_sizemax_sizedesired_capacity

      【讨论】:

        【解决方案3】:

        错误消息几乎概括了它:您的变量 action 在定义之前就已被使用(在某些情况下)。

        更具体地说,您的action 变量仅在您的else 块中定义,这意味着如果您的条件servers_need_to_be_started(group) 为真,则永远不会定义action

        因此,只需使用一些默认值(例如空字符串)定义 if/else 块的 outside 变量,然后根据需要在 else 块中对其进行修改:

        for group in auto_scaling_groups:
            action = ""
            if servers_need_to_be_started(group):
                pass
            else:
                action = "Stopping"
                min_size = 0
                max_size = 0
                desired_capacity = 0
        
            print("Version is {}".format(botocore.__version__))
        
            print (action + ": " + group)  #Error in this line 
            response = client.update_auto_scaling_group(
                AutoScalingGroupName=group,
                MinSize=min_size,
                MaxSize=max_size,
                DesiredCapacity=desired_capacity,
            )
        
            print (response)
        

        【讨论】:

          猜你喜欢
          • 2017-08-10
          • 2020-01-16
          • 2019-12-05
          • 2017-09-19
          • 2020-09-26
          • 2022-01-02
          • 2019-03-22
          • 2019-01-24
          • 2021-07-01
          相关资源
          最近更新 更多