In the post FIFO and LIFO queues in python I shown how to use queues in python 3.
Python provides also priority queues.
You can use such a queue when the processing order of the items in a queue needs to be based on the importance of the items.
In a priority queue, the most important element will always be popped first, so in a priority queue you have to push a tuple of at least two elements: the priority and the content. The element with the lowest value for the priority will be popped.
The following program populates a priority queue with random priority values and some text.
if __name__ == '__main__': # python2 Queue.Queue() and Queue.LifoQueue() PRIO_QUEUE = queue.PriorityQueue() print('Populating the priority queue') for counter in range(10): time.sleep(0.4) prio = randint(0, 9) strn = "data - "+ str(prio) + " " + str(time.asctime()) PRIO_QUEUE.put((prio, strn)) print((prio, strn))
then it pops data from the priority queue and prints out the popped items
print('Getting data from the priority queue') print('=========================') for counter in range(10): prio, strn = PRIO_QUEUE.get() print((prio, strn))
You can find the full source code with the latest updates on my github: prio_queue.py
When you run the prio_queue.py program it will ouput something like the following
python prio_queue.py Populating the priority queue (8, 'data - 8 Fri Dec 15 06:51:31 2017') (1, 'data - 1 Fri Dec 15 06:51:31 2017') (4, 'data - 4 Fri Dec 15 06:51:32 2017') (2, 'data - 2 Fri Dec 15 06:51:32 2017') (6, 'data - 6 Fri Dec 15 06:51:32 2017') (4, 'data - 4 Fri Dec 15 06:51:33 2017') (6, 'data - 6 Fri Dec 15 06:51:33 2017') (2, 'data - 2 Fri Dec 15 06:51:34 2017') (4, 'data - 4 Fri Dec 15 06:51:34 2017') (5, 'data - 5 Fri Dec 15 06:51:34 2017')
as you can see, it pushes data with random priority. And, then:
Getting data from the priority queue ========================= (1, 'data - 1 Fri Dec 15 06:51:31 2017') (2, 'data - 2 Fri Dec 15 06:51:32 2017') (2, 'data - 2 Fri Dec 15 06:51:34 2017') (4, 'data - 4 Fri Dec 15 06:51:32 2017') (4, 'data - 4 Fri Dec 15 06:51:33 2017') (4, 'data - 4 Fri Dec 15 06:51:34 2017') (5, 'data - 5 Fri Dec 15 06:51:34 2017') (6, 'data - 6 Fri Dec 15 06:51:32 2017') (6, 'data - 6 Fri Dec 15 06:51:33 2017') (8, 'data - 8 Fri Dec 15 06:51:31 2017')
it pops data starting with lowest priorities.
Gg1