简体   繁体   English

等待信号开始从python中的另一个进程生成数据

[英]Wait for signal to start generating data from another process in python

I have two independent processes in python: producer and consumer . 我在python中有两个独立的进程: 生产者消费者 Producer generates files and consumer does some processing on files. 生产者生成文件,而使用者对文件进行一些处理。

To test both applications, I find myself constantly starting two programs, and producer has a delay function, etc. which is a pain. 为了测试这两个应用程序,我发现自己不断地启动两个程序,并且生产者具有延迟功能等,这很痛苦。

What is the quickest way to implement some kind of signaling machinery in python so that consumer says "GO!" 在python中实现某种信令机制以使消费者说“ GO!”的最快方法是什么? and producer starts doing things it does. 生产者开始做它做的事情。

This way I can have producer running all the time. 这样,我可以让生产者一直运行。

One simple way to do this (you didn't mention what platform(s) you care about, so I'll assume you want something cross-platform) is a UDP socket with a known port. 一种简单的方法(您没有提到您关心的平台,所以我假设您需要跨平台的东西)是带有已知端口的UDP套接字。 If the consumer just listens on localhost port 12345, it can block on a sock.recvfrom call every time it needs to wait, and the producer can do a sock.sendto to notify it. 如果使用者仅在本地主机端口12345上侦听,则它可以在每次需要等待时阻塞sock.recvfrom调用,而生产者可以执行sock.sendto来通知它。

For example, here's a consumer: 例如,这是一个消费者:

#!/usr/bin/env python

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('127.0.0.1', 12345))

while True:
    dummy, addr = sock.recvfrom(1024)
    # work on files until done

And a producer: 和制作人:

#!/usr/bin/env python

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

for thing in things:
    # produce files for consumer
    sock.sendto(b'X', ('127.0.0.1', 12345))

Other things to consider: 要考虑的其他事项:

  • On Unix, there are advantages to using Unix sockets instead of UDP sockets. 在Unix上,使用Unix套接字而不是UDP套接字有很多优点。
  • On Windows, there are advantages to using named pipes instead of sockets. 在Windows上,使用命名管道而不是套接字有很多优点。
  • You may want to make the consumer a daemon (with or without a built-in "service" tool to start and stop it) on Unix or a Windows service on Windows. 您可能要在Unix上或Windows的Windows服务上使使用者成为守护程序 (带有或不带有内置的“服务”工具来启动和停止它)。 (You can even merge the service tool into the producer, so, eg, the default behavior is to start a consumer if one isn't there, then shut it down when it's done, but it can also be used to launch a long-running consumer in the background.) (您甚至可以将服务工具合并到生产者中,因此,例如,默认行为是在不存在时启动消费者,然后在完成后将其关闭,但也可以用于启动长期服务,在后台运行消费者。)
  • You can extend this pretty easily to send more than just an empty notification—eg, send a different message if you're done producing. 您可以很轻松地扩展此功能,以发送不仅仅是空的通知,例如,如果制作完成,则发送不同的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM