Python 将队列传递给动态连接的进程
我正在寻找一种在守护进程(Python 将队列传递给动态连接的进程,python,ipc,python-3.5,Python,Ipc,Python 3.5,我正在寻找一种在守护进程(Mainprogram)和其他进程(bot)之间有效通信的方法。这里的困难在于,我需要能够让机器人随时进出这条通信路径 到目前为止,我使用Unix域套接字在进程之间进行通信。当我进行一对一的交流时,这已经足够好了。在我的新设置中,我不想依赖它们-它可以是任何数量的n的bot发送数据,并且它们不同步传输 从逻辑上讲,我转到了queue.queue来解决这个问题。拥有一个Queue对象,而main可以稳定地从中拉出,这正是我所需要的 问题是,我需要机器人能够进出我的通信网络
Main
program)和其他进程(bot)之间有效通信的方法。这里的困难在于,我需要能够让机器人随时进出这条通信路径
到目前为止,我使用Unix域套接字
在进程之间进行通信。当我进行一对一的交流时,这已经足够好了。在我的新设置中,我不想依赖它们-它可以是任何数量的n
的bot
发送数据,并且它们不同步传输
从逻辑上讲,我转到了queue.queue
来解决这个问题。拥有一个Queue
对象,而main
可以稳定地从中拉出,这正是我所需要的
问题是,我需要机器人
能够进出我的通信网络,因此我需要将队列
传递给新注册的进程
我尝试使用UDS
将我的Queue
分发到任何挂接到main
的进程,但这不是一个选项,因为Queue
不可拾取。另外,accept()
似乎也不适用于UDS
(这很有意义,因为它是一个类似文件的文件)
代码:
显而易见的替代方案是通过TCP
socket接收数据,将其放入队列中
,然后从那里开始工作,但这是唯一的可能性吗
我见过multiprocessing.connection.Listener
,但我认为这与自制的TCP
解决方案差不多,不是吗
class QueueDistributor(threading.Thread):
def __init__(self, q, addr, name='Queue Distributor'):
""" constructor, setting initial variables """
self._stopevent = threading.Event()
self.q = q
self.addr = addr
threading.Thread.__init__(self, name=name)
def run(self):
""" main control loop """
if os.path.exists(self.addr):
os.remove(self.addr)
sock = socket(AF_UNIX, SOCK_STREAM)
sock.settimeout(1)
sock.bind(self.addr)
sock.listen(1)
while not self._stopevent.isSet():
try:
client, addr = sock.accept()
try:
client.send(self.q)
except timeout:
continue
except Exception:
traceback.print_exc(file=sys.stdout)
except timeout:
continue
except Exception:
traceback.print_exc(file=sys.stdout)
sock.close()
def join(self, timeout=None):
""" Stop the thread. """
self._stopevent.set()
threading.Thread.join(self, timeout)
class Homer:
def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null',
stderr='/dev/null'):
self.pidfile = pidfile
self.redirects = stdin, stdout, stderr
self.address = '/tmp/homer.uds'
self.running = False
self.q = Queue()
self.q_distributor = QueueDistributor(self.q, self.address)
# Open up file descriptors with zero buffering
self.trades = open('/tmp/trades.csv', 'ab', buffering=0)
self.tickers = open('/tmp/tickers.csv', 'ab', buffering=0)
self.books = open('/tmp/books.csv', 'ab', buffering=0)
# ...
def handle_data(self, data):
...
def run(self):
self.running = True
# Launch queue distribution Thread
self.q_distributor.start()
while self.running:
try:
data = self.q.get(timeout=0.1)
self.handle_data(data)
except Empty:
continue
except NotImplementedError as e:
log.error(e)
continue
# Shutdown Queue Distributor
self.q_distributor.join()