在 python 中使用队列
问题描述
我正在尝试在 Eclipse(使用 PyDev)中运行以下命令,但我不断收到错误消息:
q = queue.Queue(maxsize=0)NameError:未定义全局名称队列"
我已经检查了文档,看起来应该是这样放置的.我在这里错过了什么吗?PyDev 是这样工作的吗?或在代码中遗漏了什么?感谢大家的帮助.
从队列导入 *定义工人():而真:项目 = q.get()做工作(项目)q.task_done()定义主():q = queue.Queue(maxsize=0)对于我在范围内(num_worker_threads):t = 线程(目标 = 工人)t.daemon = 真t.start()对于 source() 中的项目:q.put(项目)q.join() # 阻塞直到所有任务完成主要的()
使用:Eclipse SDK
版本:3.8.1内部版本号:M20120914-1540
和 Python 3.3
解决方案你做
从队列导入 *
这已经从 queue
模块中导入了所有类.将该行更改为
q = 队列(maxsize=0)
<块引用>
小心:应避免通配符导入(来自 import *),因为它们使命名空间中存在哪些名称变得不清楚,从而使读者和许多自动化工具感到困惑".(Python PEP-8)
作为一种替代方法,可以使用:
从队列导入队列q = 队列(最大尺寸=0)
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
解决方案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)
相关文章