Loop only runs for one iteration, why?


#1

here is my code.

def get_flash_file():
    print("create flash file")
    
    # open a 512 bytes FlashFileStream at address 0x80E0000
    ff = flash.FlashFileStream(flash_address,512)
    
    print("reading flash file")
    
    for i in range(30):
        print(i,"->",str(ff[i]))
    
    print("writing flash file")
    
    sleep(1000)
    
    hh = {
        "type":"thing",
        "data":23.5
    }
    
    ds = json.dumps(hh)
    
    # save length and json to flash
    ff.write(len(ds))
    ff.write(ds)
    
    ff.flush()
    
    ff.seek(0,streams.SEEK_SET)
    
    print("reading flash file")
    
    n = ff.read_int()
    s = b''
    for i in range(n + 4):
        print(i,"->",str(ff[i]))
        s.append(ff[i])
    str.append(b'0')
    print("read " + str(s))

the output is :

create flash file
reading flash file
0 -> 28
1 -> 0
2 -> 0
3 -> 0
4 -> 123
5 -> 34
6 -> 116
7 -> 121
8 -> 112
9 -> 101
10 -> 34
11 -> 58
12 -> 34
13 -> 116
14 -> 104
15 -> 105
16 -> 110
17 -> 103
18 -> 34
19 -> 44
20 -> 34
21 -> 100
22 -> 97
23 -> 116
24 -> 97
25 -> 34
26 -> 58
27 -> 50
28 -> 51
29 -> 46
writing flash file
reading flash file
0 -> 28

the read only runs for one iteration it seems.
program flow appears to stop as functions called afterward are not called.
Any ideas? (if we had a repl…)


#2

Hi @jimmyhoughjr,

there is not a repl, but we have exception handling :sunglasses:
From what I see your code creates s as a bytes object and then calls the append method which is not available for immutable types, causing an AttributeError just like standard Python.
You can catch that exception with a simple

try:
    s = b''
    s.append(b'c')
except Exception as e:
    print(e)

which you can leave while testing and remove in production.
Let me know if this helps you :slight_smile: