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.

No comments:

Post a Comment