Using Queue in python

被刻印的时光 ゝ 提交于 2019-12-04 16:39:48

问题


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


回答1:


You do

from queue import *

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

q = Queue(maxsize=0)



回答2:


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




回答3:


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.




回答4:


You Can install kombu with pip install kombu

and then Import queue Just like this

from kombu import Queue



来源:https://stackoverflow.com/questions/14584958/using-queue-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!