Queue/Priority Needed

Mariano Mara mariano.mara at gmail.com
Thu Jul 3 00:37:15 EDT 2008


Keith Nation wrote:
> I'm still very new to python, and I have a question about how to
> prioritize jobs in a queue.
>
You can use the python 2.6 priority queue implementation:

$ python
Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import heapq
 >>> import Queue
 >>>
 >>> class PriorityQueue(Queue.Queue):
...     """Variant of Queue that retrieves open entries in
...     priority order (lowest first).
...     Entries are typically tuples of the form:  (priority number,
...     data)
...     This class can be found at: Python-2.6a3/Lib/Queue.py
...     """
...     maxsize = 0
...     def _init(self, maxsize):
...         self.queue = []
...     def _qsize(self, len=len):
...         return len(self.queue)
...     def _put(self, item, heappush=heapq.heappush):
...         heappush(self.queue, item)
...     def _get(self, heappop=heapq.heappop):
...         return heappop(self.queue)
...
 >>> class example(object):
...     def __init__(self, p1, p2, p3, p4):
...         self.p1 = p1
...         self.p2 = p2
...         self.p3 = p3
...         self.p4 = p4
...
 >>> pq = PriorityQueue()
 >>> ex = example('Task1', 'v03', '-start', 'Bonnie')
 >>> pq.put((1, ex))
 >>> ex = example('Task3', 'v01', '-start', 'Bob')
 >>> pq.put((3, ex))
 >>> ex = example('Task2', 'v01', '-start', 'Billy')
 >>> pq.put((2, ex))
 >>> pr, ex = pq.get() # prints task 1
 >>> print ex.p1, ex.p2, ex.p3, ex.p4
Task1 v03 -start Bonnie
 >>> pr, ex = pq.get() # prints task 2
 >>> print ex.p1, ex.p2, ex.p3, ex.p4
Task2 v01 -start Billy



More information about the Python-list mailing list