Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Queue in python

Tags:

I'm trying to run the following in Eclipse (using PyDev) and I keep getting error :

q = queue.Queue(maxsize=0) NameError: global name 'queue' is not defined

I've checked the documentations and appears that is how its supposed to be placed. Am I missing something here? Is it how PyDev works? or missing something in the code? Thanks for all help.

from queue import *  def worker():     while True:         item = q.get()         do_work(item)         q.task_done()  def main():      q = queue.Queue(maxsize=0)     for i in range(num_worker_threads):          t = Thread(target=worker)          t.daemon = True          t.start()      for item in source():         q.put(item)      q.join()       # block until all tasks are done  main() 

Using: Eclipse SDK

Version: 3.8.1 Build id: M20120914-1540

and Python 3.3

like image 340
Bain Avatar asked Jan 29 '13 14:01

Bain


People also ask

How queue is used in Python?

Like stack, queue is a linear data structure that stores items in First In First Out (FIFO) manner. With a queue the least recently added item is removed first. A good example of queue is any queue of consumers for a resource where the consumer that came first is served first.

How do you add to a queue in Python?

Answer: In Python, to insert the element in the queue, the “ put() ” function is used. It is known as an enqueue operation. To delete the element in the queue the “ get() ” function is used. It is known as the dequeue operation.

Is queue a data type in Python?

What is a Queue and how to implement one in Python. A queue in programming terms is an Abstract Data Type that stores the order in which items were added to the structure but it only allows additions to the end of the queue while allowing only removals from the front of the queue.


2 Answers

You do

from queue import * 

This imports all the classes from the queue module already. Change that line to

q = Queue(maxsize=0) 

CAREFUL: "Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools". (Python PEP-8)

As an alternative, one could use:

from queue import Queue  q = Queue(maxsize=0) 
like image 65
David Robinson Avatar answered Oct 29 '22 02:10

David Robinson


That's because you're using : from queue import *

and then you're trying to use :

queue.Queue(maxsize=0)  

remove the queue part, because from queue import * imports all the attributes to the current namespace. :

Queue(maxsize=0)  

or use import queue instead of from queue import *.

like image 28
Ashwini Chaudhary Avatar answered Oct 29 '22 03:10

Ashwini Chaudhary