Problems with append incremetando until the infinity in Python

Asked

Viewed 41 times

0

I’m doing a program that scans 35 bits on a piece of equipment, storing reference bits in an array. The logic to know if any bit has changed since the last reading, always saves the previous result and compares with the current one with the current one. In this part, everything works as expected.

from pyModbusTCP.client import ModbusClient
import time

SERVER_HOST = "10.0.0.66"
SERVER_PORT = 555

c = ModbusClient()
c.host(SERVER_HOST)
c.port(SERVER_PORT)

endereco = 0
bit = []
bit.clear()

while True:
    
    if not c.is_open():
        if not c.open():
            print("não é possível conectar em "+SERVER_HOST+":"+str(SERVER_PORT))    

    if c.is_open():

        bit_atual = c.read_coils(endereco, 1)
        bit.append(bit_atual)
 
        if bit_atual:
            if  bit_atual != bit[endereco]:
                print("bit[" + str(endereco)+"] = " + str(bit_atual)+ " -> MUDEI ")
                
            else:
                print("bit[" + str(endereco)+"] = " + str(bit_atual))
            
                  
        bit[endereco] = bit_atual
        endereco = endereco + 1
    
        if endereco == 35: 
            endereco = 0
            time.sleep(2)
            print("  ")
            print("  ") 

The problem I’m having is that when using the "append" to add elements in the array it always adds 35 more lines to each while loop, being I only need the first 35 lines.

If I leave running a while and do a Len(bit) the value is already huge, at some point it ends up breaking the limit.

I thought to use a bit.clear() at the end of the while loop, but I can’t because I always use the previous read to compare to the current one.

I tried to change the

bit.append(bit_atual)

for

bit.append[endereco]=bit_atual

Because I believe it will always replace the value with its address, but it returns with the error:

bit[endereco]=bit_atual
IndexError: list assignment index out of range

Can anyone give me a light? Is there a way to limit an append? or some other way? Thank you

*bit_current are boolean values.

1 answer

0


Like the append is called within a loop infinite, of course the list will grow indefinitely.

If the idea is that it has at most 35 elements, I think the best is to create it now with this size, there loop you only care about checking the position relative to the address. Something like this:

tamanho_maximo = 35
endereco = 0
# cria a lista com 35 posições (inicialmente com o valor None)
bit = [None] * tamanho_maximo

while True:
    if not c.is_open():
        if not c.open():
            print(f"não é possível conectar em {SERVER_HOST}:{SERVER_PORT}")    

    if c.is_open():
        bit_atual = c.read_coils(endereco, 1)
        if bit_atual:
            if bit[endereco] is not None and bit_atual != bit[endereco]:
                print(f"bit[{endereco}] = {bit_atual} -> MUDEI ")
            else:
                print(f"bit[{endereco}] = {bit_atual}")

        bit[endereco] = bit_atual
        if endereco == tamanho_maximo - 1:
            time.sleep(2)
            print("  \n  ")
        endereco = (endereco + 1) % tamanho_maximo

Thus, the list starts with 35 values equal to None. Then, just see if the value of the current bit is not None (for the None indicates that it has not yet been set), and if not, see if it has changed.

I also changed other things: I used f-string instead of concatenating strings (available from Python 3.6), and using the operator % (rest of the division) to increase the value of endereco, so it already returns to zero when it reaches the maximum size.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.