samedi 9 janvier 2016

Python Threading not stopping

Vote count: 0

first try at threading in python, the threading is working after following a post on Stack however I can't stop the thread with ctrl-c despite having a terminate method in my class called with a keyboard interrupt.

Basically I'm polling a temp sensor in the background and using a thread to do that whilst the main body of the code is watching GPIO inputs, everything is working fine, its just threading thats baffling me/

(there's intention overkill re print messages so I can understand where its going wrong etc)

class GetClimate(threading.Thread):
  def __init__(self):
    self._running = True
    print "Data Collection STARTED"
  def terminate(self):
    self._running = False
    print "Data Collection ENDED"
  def run(self):
    while self._running is True:
      ts = time.time()
      global GARAGE_HUM, GARAGE_TEMP
      timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
      GARAGE_HUM, GARAGE_TEMP = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4)
      if GARAGE_HUM is not None and GARAGE_TEMP is not None:
        print timestamp + " - Temperature: %.1f c" % GARAGE_TEMP
        print timestamp + " - Humidity:    %.1f %%" % GARAGE_HUM
        time.sleep(5) # seconds between sample

#---------Start Getting Climate data------------

def StartClimate():
    c = GetClimate()
    t = threading.Thread(target=c.run)
    t.start()
    print "Started Climate"
#--------Stop Climate Data----------------------
def StopClimate():
    print "Called Climate stop .."
    c = GetClimate()
    c.terminate()
    print "Stopped Climate"

When ctrl-c is used its calling the StopClimate() function OK as it outputs:

Data Collection STARTED
Started Climate
..Ready
2016-01-09 20:48:45 - Temperature: 24.8 c
2016-01-09 20:48:45 - Humidity:    51.9 %
Shutdown requested...exiting
Called Climate stop ..
Data Collection STARTED
Data Collection ENDED
Stopped Climate
^C2016-01-09 20:48:51 - Temperature: 24.8 c
2016-01-09 20:48:51 - Humidity:    51.9 %
2016-01-09 20:48:57 - Temperature: 24.7 c
2016-01-09 20:48:57 - Humidity:    51.8 %

.... as you can see the thread is still polling.

asked 33 secs ago

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at http://ift.tt/jcXqJW.



Python Threading not stopping

Aucun commentaire:

Enregistrer un commentaire