Monday, April 30, 2018

116: Python Threads

This isn't my usual sort of interest. And I'm not very fond of Python -- too many ways of doing the same thing (Go golang!). Anyway. I wanted to program an async task that accepts input that might modify what's happening in the main loop. I'm only posting this code snippet because it took me 20-ish Googles and a dozen source tweaks to get this to work. And the posted examples are way more arcane.


# Simple Python Threading example that puts blocking 
# I/O in its own asynchronous thread
import os, time
import threading

rv = '' # to pass data to the loop

def ck_file() : # the I/O thread
    global rv

    while True :
        if os.path.exists('cmd') :
            f = open('cmd', 'r')
            rv = f.readline()
            f.close()
            os.remove('cmd') # so it's only reported once
        time.sleep(5)

t = threading.Thread(target=ck_file) # black magic!
t.daemon = True # needed to cause the thread to exit

t.start()       # never runs without this

# main loop
ct = 0
while True :  # where you'd do something useful
    time.sleep(10)
    ct += 1
    print "ct=", ct
    if rv != '' : #data entered
        print "RV:", rv
        rv = ''   
    if ct == 10 : break # it's just an example, after all


Note: the daemon line is important. Probably should be the default. Otherwise the thread never exits.

So, in the spirit of an oyster turning a grain of sand into a pearl I have posted this pearl (?) caused by my aggravation.

Monday, April 9, 2018

115: SSH over the Internet!
(why didn't I find this sooner?)

There are several services available. I chose remot3.it. Their web page leaves certain info gaps (duh) but with my daughter's help I got 3 Pi Zeros connected. Just like local SSH! Unlike just replacing files you can interactively update cron or edit a file with nano. And the "private" account is free (so far). Unfortunately, you have to go through several web clicks to get a sort-of "session ID number" (my term) to do a remote SSH connection. Still, very nice.