UnboundLocalError:局部变量' b'在分配之前引用

时间:2015-08-27 14:37:19

标签: python

我一直收到这个错误但是我已经在函数#中定义了局部变量来获取数据检查点大小。最初我认为这个错误可能是因为缩进,但这对我来说也不起作用。

data_checkpoint_size = cclient.samples.list(meter_name ='checkpoint.size')
        data_checkpoint_length = cclient.samples.list(meter_name ='checkpoint.length')
        data_checkpoint_pause = cclient.samples.list(meter_name ='checkpoint.pause')
        data_cpu= cclient.samples.list(meter_name ='cpu')
        data_incomingbytes = cclient.samples.list(meter_name ='incoming.network.bytes')
        data_outgoingbytes = cclient.samples.list(meter_name ='outgoing.network.bytes')





      def counterVolume(data_cpu, data_incomingbytes, data_outgoingbytes, data_checkpoint_size, data_checkpoint_length, data_checkpoint_pause):
          for each in data_cpu:
            a = each.counter_volume
          for each in data_incomingbytes:
            b = each.counter_volume
          for each in data_outgoingbytes:
            c = each.counter_volume
          for each in data_checkpoint_size:
            d = each.counter_volume
          for each in data_checkpoint_length:
            e = each.counter_volume
          for each in data_checkpoint_pause:
            f = each.counter_volume
          pubnub.publish(channel='channel', message= {'cpu': a, 'incoming_bytes': b, 'outgoing_bytes': c, 'checkpoint_size': y, 'checkpoint_length': x, 'checkpoint_pause': z})


counterVolume(data_cpu, data_incomingbytes, data_outgoingbytes, data_checkpoint_size, data_checkpoint_length, data_checkpoint_pause)

1 个答案:

答案 0 :(得分:3)

for each in data_incomingbytes:
   b = each.counter_volume

如果data_incomingbytes为空,该怎么办?然后循环将不会运行,并且不会分配b。发生这种情况的可能性就是Python所抱怨的。无论循环是否运行,您都需要分配给b(以及所有其他变量)。