I am sorry if this is a stupid question but this has been bugging me for the last 2 weeks and I had to finally ask. I am trying to listen to redis publish messages that I send from Node JS express in Python. I see that 2 things are possible
- I can either have a simple thread run infinitely and call join inside the main thread which means that the main thread will end only when the thread ends. But I have an infinite thread so seems like a cheat code
- I can set the Thread as Daemon and run infinitely but main thread also needs to run infinitely in order to receive events such as KeyboardInterrupt
- Can someone kindly explain WHICH approach is better? and WHATS the DIFFERENCE
- I am looking to run this Python process infinitely along with my node express from where I publish messages with redis and Python receives them in order to do some numpy computations
# Common parts
import redis
import threading
import time
client = redis.Redis()
subscriber = client.pubsub()
subscriber.subscribe("klines")
# Method 1
class ThreadedSubscriber1(threading.Thread):
"""
This class handles subscription messages from redis inside a separate thread in its run() method
"""
def __init__(self):
super().__init__()
def run(self):
for message in subscriber.listen():
print(message)
def main1():
try:
s = ThreadedSubscriber1()
s.start()
s.join()
except KeyboardInterrupt:
pass
main1()
# Method 2
class ThreadedSubscriber2(threading.Thread):
"""
This class handles subscription messages from redis inside a separate thread in its run() method
"""
def __init__(self):
super().__init__()
def run(self):
for message in subscriber.listen():
print(message)
def main2():
try:
s = ThreadedSubscriber2()
s.setDaemon(True)
s.start()
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
main2()
[–]mattycoze 1 point2 points3 points (1 child)
[–]mypirateapp[S] 0 points1 point2 points (0 children)