Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing contents of a Queue in Python

If I am using the python module queue.Queue, I want to be able to print out the contents using a method that does not pop the original queue or create a new queue object.

I have tried looking into doing a get and then putting the contents back but this is too high cost.

# Ideally it would look like the following
from queue import Queue
q = Queue()
q.print()
q.put(1)
q.print()

>> [] # Or something like this
>> [1] # Or something like this
like image 246
Interlooper Avatar asked Feb 12 '19 18:02

Interlooper


Video Answer


3 Answers

>>> print(list(q.queue))

Does this work for you?

like image 152
Aviral Verma Avatar answered Oct 18 '22 19:10

Aviral Verma


Assuming you are using python 2. You can use something like this:

from queue import Queue
q = Queue.Queue()
q.put(1)
q.put(2)
q.put(3)
print q.queue

You can also loop on it :

for q_item in q.queue:
    print q_item

But unless you are dealing with threads, I would use a normal list as a Queue implementation.

like image 3
Paulo Cirino Avatar answered Oct 18 '22 19:10

Paulo Cirino


Sorry, I am a bit late to answer this question, but going by this comment, I extended the Queue in the multiprocessing package as per your requirements. Hopefully it will help someone in the future.

import multiprocessing as mp
from multiprocessing import queues


class IterQueue(queues.Queue):

    def __init__(self, *args, **kwargs):
        ctx = mp.get_context()
        kwargs['ctx'] = ctx
        super().__init__(*args, **kwargs)

    # <----  Iter Protocol  ------>
    def __iter__(self):
        return self

    def __next__(self):
        try:
            if not self.empty():
                return self.get()  # block=True | default
            else:
                raise StopIteration
        except ValueError:  # the Queue is closed
            raise StopIteration

Given below is a sample usage of this IterQueue I wrote:

def sample_func(queue_ref):
    for i in range(10):
        queue_ref.put(i)


IQ = IterQueue()

p = mp.Process(target=sample_func, args=(IQ,))
p.start()
p.join()

print(list(IQ))  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

I have tested this IterQueue for even a few more complex scenarios, and it seems to be working fine. Let me know if you think this works, or it could fail in some situation.

like image 2
Archit Kapoor Avatar answered Oct 18 '22 19:10

Archit Kapoor