如何在某个特定时间退出发电机? [英] How to exit from a generator at some specific time?

查看:73
本文介绍了如何在某个特定时间退出发电机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Twitter Streaming API上的推文.连接到API后,我得到了一个生成器.

I'm reading tweets from Twitter Streaming API. After connecting to the API, I'm getting a generator.

我正在遍历收到的每个tweet,但是我想从迭代器退出,例如在18PM.收到每条推文后,我正在检查它是否晚于指定的时间戳并停止.

I'm looping through each tweet received but I want to exit from the iterator, say, at 18PM. After receiving each tweet, I'm checking if it's later than the specified timestamp and stopping.

问题是我没有足够频繁地收到推文.因此,我可以在17:50收到一个,然后在19PM收到另一个.那是当我发现时间已经过去并且我需要停下来的时候.

The issue is that I'm not receiving tweets frequently enough. So, I could receive one at 17:50 and the next one at 19PM. That's when I'll find out that the time has passed and I need to stop.

是否有一种方法可以强制在下午18点准确停止?

Is there a way to force the stop at 18PM exactly?

这是我的代码的高级视图:

Here's a high-level view of my code:

def getStream(tweet_iter):
    for tweet in tweet_iter:
        #do stuff
        if time_has_passed():
            return

tweet_iter = ConnectAndGetStream()
getStream(tweet_iter)

推荐答案

为生产者创建一个单独的线程,并使用 threading.Event 来停止制片人.

Create a separate thread for the producer and use a Queue to communicate. I also had to use a threading.Event for stopping the producer.

import itertools, queue, threading, time

END_TIME = time.time() + 5  # run for ~5 seconds

def time_left():
    return END_TIME - time.time()

def ConnectAndGetStream():             # stub for the real thing
    for i in itertools.count():
        time.sleep(1)
        yield "tweet {}".format(i)

def producer(tweets_queue, the_end):   # producer
    it = ConnectAndGetStream()
    while not the_end.is_set():
        tweets_queue.put(next(it))

def getStream(tweets_queue, the_end):  # consumer
    try:
        while True:
            tweet = tweets_queue.get(timeout=time_left())
            print('Got', tweet)
    except queue.Empty:
        print('THE END')
        the_end.set()

tweets_queue = queue.Queue()  # you might wanna use the maxsize parameter
the_end = threading.Event()
producer_thread = threading.Thread(target=producer,
                                   args=(tweets_queue, the_end))
producer_thread.start()
getStream(tweets_queue, the_end)
producer_thread.join()

这篇关于如何在某个特定时间退出发电机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆