English 中文(简体)
粉碎:奎特。 工作例外
原标题:Python: Queue.Empty Exception Handling

在与一些人就甲型六氯环己烷例外处理问题进行了简短辩论之后,我觉得我 throw弃了它。

METHOD 1:

import Queue

q = Queue.Queue()

try:
    task=q.get(False)
    #Opt 1: Handle task here and call q.task_done()
except Queue.Empty:
    #Handle empty queue here
    pass

#Opt2: Handle task here and call q.task_done()

METHOD 2:

import Queue

q = Queue.Queue()

if q.empty():
    #Handle empty queue here
else:
    task = q.get()
    #Handle task here
    q.task_done()

一种论点是,方法1是错误的,因为空洞并非错误,因此不应使用Quue处理。 就业例外。 此外,如果你认为任务处理部分可能很大的话,那么如果将这种方式编码的话,就会使分解变得更加困难。

另一种论点是,要么在沙尔接受,要么在审判之外处理任务,要么如果任务处理规模很大,则会协助偷渡,尽管一致认为这可能比使用方法2更看问题。

意见?

UPDATE: A little more info after answer 1 came through.... The debate was started after method 1 was using in some multithreaded code. In which case, the code will acquire the lock (from a threading.Lock object) and release it either once the task it returned or Queue.Empty is thrown

附录 2. 我们大家不知道, object子已经安全。 看起来像尝试/例外是走路!

最佳回答

方法2是错误的,因为你在两个步骤中开展行动时,可以开展行动。 在方法2中,你检查点是否空了,然后(很快,但仍在以后)试图拿到该项目。 你们有两条read子把物品从胎盘中拿走? 空洞的陷阱仍然可能失败。 在检查后,如果在问询中添加一个物品,那是空的? 这些是各种机会之窗,这些机会之窗按照并行的法典 cr。

无论采取哪一步,它迄今为止都是更好的选择。

import Queue

q = Queue.Queue()

try:
    task = q.get(False)
except Queue.Empty:
    # Handle empty queue here
    pass
else:
    # Handle task here and call q.task_done()

“例外应当是错误”。 例外只是另一种通信渠道,使用它们。 此处使用“e”条款来缩小例外条款的范围。

问题回答

如果是多读/多处理法(这是使用任何途径的良好理由),那么肯定的方法1。 在<条码>q.empty() 电话和q.get( 电话之间,心脏的杰克本可能偷走了你的条条arts!

一种论点是,方法1是错误的,因为空洞并非错误,因此不应使用Quue处理。 就业例外

一种例外不一定是“承运人”,它是一个一般的流动控制机制,在少数情况下(SysExit、制止渗透等)的确如此使用。

The good question here is: what will be the most common case - empty or non-empty queue. Unless you know for sure, you want to AskBeforeYouLeap, cause it s very probably way cheaper.

面对同一问题,不寻找Queue模块;我知道这大约一年后,但未来的读者可能会发现以下示范例子:

from queue import Queue, Full, Empty
q = Queue(maxsize=3)    # finite queue, maxsize <= 0 -> infinite queue

# enqueue a couple of items
q.put( a )
q.put( b )

# trying to dequeue excessively
for _ in range(4):
    try:
        print(f dequeued: {q.get(block=False)} )

    except Empty:
        print( empty queue! )

# trying to enqueue excessively
for ch in [ a ,  b ,  c ,  d ]:
    try:
        print(f enqueueing : {ch} -> , end=   )
        q.put(ch, block=False)
        print( success :) )

    except Full:
        print( full queue :( )

and here is the sample output:

dequeued: a
dequeued: b
empty queue!
empty queue!
enqueueing : a -> success :)
enqueueing : b -> success :)
enqueueing : c -> success :)
enqueueing : d -> full queue :(

Please note, by default, get() and put() are both blocking methods (block=True) and will block the process until a new item is inserted into the queue (get), or an item is consumed to allow room for a new item (put). See here for more details.

在某些法典中,我刚才写道,我需要迅速空洞,只处理最后一个项目,我认为这是最近的事件,也是我所关心的。

我基本上利用你的方法1来这样做。

# pop data from queue until it is empty and so have the most recent data:
data = self.queue.get()    # first call to the queue blocks, so when get past this line, data should be valid
try:
    while True:
        data = self.queue.get_nowait()    # subsequent calls do NOT block; overwrite data with the last valid result; this call will raise an Empty Exception after have read all data from the queue
except Empty:
    pass

如果我能正确理解斯堪的斯温特,这是我空洞的唯一好办法。

尽管如此,我还是怀着仇恨,叫APIC!

Sorry Pythonistas, its defective. There ought to be a nonblocking way that I can poll the queue for its first item and it returns None if it is empty instead of raising an Empty. Using an Exception here is a terrible choice not only because it requires an awkward try/except but also because it is awful for performance: stacktraces are expensive to generate. The code above is in a real critical section for me.

参看:Java s Queue界面污染方法;另见this问题SO。 极佳的APIC设计。

是否有第3个政党的沙丘同时执行,这种执行方法类似污染吗?





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签