如何清除python中的多处理队列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16461459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:42:19  来源:igfitidea点击:

How to clear a multiprocessing queue in python

pythonmultiprocessing

提问by FelipeG

I just want to know how to clear a multiprocessing queue in python like a normal python queue. For instance:

我只想知道如何像普通的 python 队列一样清除 python 中的多处理队列。例如:

from multiprocessing import Queue  # multiprocessing queue
from Queue import Queue            # normal queue

multi_q = Queue()
normal_q = Queue()
multi_q.clear()                    # or multi_q.queue.clear() 

'Queue' object has no attribute 'clear'

“队列”对象没有“清除”属性

normal_q.queue.clear() # This is ok

采纳答案by pcalcao

There is no direct way of clearing a multiprocessing.Queue.

没有直接的方法来清除 a multiprocessing.Queue

I believe the closest you have is close(), but that simply states that no more data will be pushed to that queue, and will close it when all data has been flushed to the pipe.

我相信您拥有的最接近的是close(),但这只是说明不会将更多数据推送到该队列,并在所有数据都已刷新到管道时将其关闭。

回答by Pavel Stárek

So, I take look at Queue class, and you may to try this code:

所以,我看看 Queue 类,你可以试试这个代码:

while not some_queue.empty():
    some_queue.get()  # as docs say: Remove and return an item from the queue.

回答by Dan H

Ask for forgiveness rather than permission; just try to empty the queue until you get the Emptyexception, then ignore that exception:

请求宽恕而不是许可;只需尝试清空队列,直到出现Empty异常,然后忽略该异常:

from Queue import Empty

def clear(q):
    try:
        while True:
            q.get_nowait()
    except Empty:
        pass

Better yet: is a built-in class missing the method you want? Subclass the built-in class, and add the method you think should be there!

更好的是:内置类是否缺少您想要的方法?继承内置类,并添加您认为应该在那里的方法!

from Queue import Queue, Empty

class ClearableQueue(Queue):

    def clear(self):
        try:
            while True:
                self.get_nowait()
        except Empty:
            pass

Your ClearableQueueclass inherits all the goodness (and behavior) of the built-in Queueclass, and has the method you now want.

您的ClearableQueue类继承了内置类的所有优点(和行为)Queue,并拥有您现在想要的方法。

Simply use q = ClearableQueue()in all places where you used q = Queue(), and call q.clear()when you'd like.

只需q = ClearableQueue()在您使用过的所有地方使用q = Queue(),并在需要q.clear()时致电。