Imo
Imo

Reputation: 1475

python loop only runs once

why does the following function only runs once a sends only one set of data. I thought for each must mean for each value in the data set.

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')


def counterVolume(data_checkpoint_size, data_checkpoint_length, data_checkpoint_pause):
  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= {'checkpoint_size': d, 'checkpoint_length': e, 'checkpoint_pause': f})

counterVolume(data_checkpoint_size, data_checkpoint_length, data_checkpoint_pause)

And I only get following as result instead of series of data. checkpoint_size, checkpoint_length and checkpoint_pause are three different meters, these are three different data streams

{
  checkpoint_length: 75,
  checkpoint_size: 5000,
  checkpoint_pause: 50
}

Upvotes: 0

Views: 1409

Answers (2)

Sam
Sam

Reputation: 20486

Like @ismailsunni said, your variables are reassigned. This makes the assumption that all data is of the same length, but it should work:

def counterVolume(data_checkpoint_size, data_checkpoint_length, data_checkpoint_pause):
    for i, size in enumerate(data_checkpoint_size):
        length = data_checkpoint_length[i]
        pause = data_checkpoint_pause[i]
        message = {
            'checkpoint_size': size .counter_volume,
            'checkpoint_length': length.counter_volume,
            'checkpoint_pause': pause.counter_volume,
        }
        pubnub.publish(channel='channel', message=message)

I'd test to make sure they're all the same length first and raise a specific exception (so it's easier to debug):

size_len = len(data_checkpoint_size)
length_len = len(data_checkpoint_length)
pause_len = len(data_checkpoint_pause)

if size_len != length_len or length_len != pause_len:
    raise Exception('Custom exception message.')

Upvotes: 2

Benjamin James Drury
Benjamin James Drury

Reputation: 2383

You are overriding d, e, and f each time each.counter_volume is called. If you wish to end up with lots of collections of returned data, you'll need something like this:

for i in range(data_checkpoint_size):
    d = data_checkpoint_size[i].counter_volume
    e = data_checkpoint_length[i].counter_volume
    f = data_checkpoint_pause[i].counter_volume
    pubnub.publish(channel='channel', message= {'checkpoint_size': d, 'checkpoint_length': e, 'checkpoint_pause': f})

It is worth noting that this assumes that all your data sets are of equal length. For a more in depth answer, you will need to provide a more in depth question regarding what it is that you are trying to achieve.

Upvotes: 2

Related Questions