Bain
Bain

Reputation: 844

Using Queue in python

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

Upvotes: 25

Views: 100646

Answers (5)

David Robinson
David Robinson

Reputation: 78600

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)

Upvotes: 27

Mahadev Vyavahare
Mahadev Vyavahare

Reputation: 91

make sure your code is not under queue.py rename it to something else. if your file name is queue.py it will try to search in the same file.

Upvotes: 2

Vladyslav
Vladyslav

Reputation: 2265

If you import from queue import * this is mean that all classes and functions importing in you code fully. So you must not write name of the module, just q = Queue(maxsize=100). But if you want use classes with name of module: q = queue.Queue(maxsize=100) you mast write another import string: import queue, this is mean that you import all module with all functions not only all functions that in first case.

Upvotes: 1

Mark Francis
Mark Francis

Reputation: 350

You Can install kombu with pip install kombu

and then Import queue Just like this

from kombu import Queue

Upvotes: -5

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

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 *.

Upvotes: 7

Related Questions