每10秒清空一次Python双端队列

时间:2019-04-07 18:36:45

标签: python

我有一个Python双端队列,每次都附加在该双端队列中。

pre_label = collections.deque(maxlen=5)
while True:
      #do something
      function(name)
      pre_label.append()

我有:

pre_label = deque(['john', 'zari', 'fai'], maxlen=3)

我希望每10秒输出以下内容:

pre_label = deque([], maxlen=3)

1 个答案:

答案 0 :(得分:0)

因此,有几种方法可以解决这个问题:

  1. 螺纹解决方案 如果您使用的是python 2,或者您不想执行异步操作,则应该可以这样做: 快速免责声明:我不会经常使用线程,因此您应该在此方面寻求更多建议。 :)
from collections import deque

deck = deque([], maxlen=3)

## Threaded solution
from threading import Thread
import time

def clear_deque():
    """ This is a small function to clear the queue and print the contents when cleared"""
    global deck  # You should probably avoid globals, but we need a reference to the underlying object to make the clear actually work. 
    while(True):
        time.sleep(3)  # you'd want to increase this to 10. Also, sleeping at the start to allow some time before the clear to happen the first time.
        contents = list(deck)
        deck = deque([], maxlen=3)
        print("\n |> Deck = {}".format(contents))

t = Thread(target=clear_deque)  # Making a new thread to call this one function
t.daemon=True  # Marking the thread as a daemon, so that it can be killed when the program exits normally
t.start()  # annnd starting the thread!

# And a dumb loop to verify the functionality
while True:
    v = input("Add stuff> ")
    deck.append(v)

t.join()
  1. 如果您使用的是python 3,则可以使用异步工作程序来实现类似的解决方案。此示例演示了如何执行此操作,但是如果您使用异步路由,则需要确保所有长时间运行的进程都是异步的,因此可能需要进行大量的重新架构。
import asyncio
import random
from collections import deque

deck = deque([], maxlen=10)

async def clear_deque():
    global deck
    while True:
        await asyncio.sleep(3)
        contents = list(deck)
        print(f"\n |> Deck contents: {contents}")
        deck = deque([], maxlen=10)


async def add_to_deque():
    while True:
        await asyncio.sleep(random.random())
        v = random.randint(1, 10)
        print(f"Adding: {v}")
        deck.append(v)


loop = asyncio.get_event_loop()
actions = asyncio.gather(add_to_deque(), clear_deque())
loop.run_until_complete( actions )