我有一个线程插入 queueStream(此处未显示)和 FlowController,如果队列不为空,FlowController 是另一个从队列中弹出的线程。
我使用 addToQueue() 中的调试代码验证了数据已正确插入队列
问题是,FlowController 中的“if queueStream”语句总是将 queueStream 视为空,而是转到 else 语句。
我是 Python 新手,我觉得我错过了一些简单的范围规则。我正在使用“全局队列流”,但这似乎没有做任何事情。
谢谢你的帮助。
from stream import *
from textwrap import TextWrapper
import threading
import time
queueStream = []
class FlowController(threading.Thread):
def run(self):
global queueStream
while True:
if queueStream:
print 'Handling tweet'
self.handleNextTweet()
else:
print 'No tweets, sleep for 1 second'
time.sleep(1)
def handleNextTweet(self):
global queueStream
status = queueStream.pop(0)
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
def addToQueue(status):
print 'adding tweets to the queue'
queueStream.append(status)
#debug
if queueStream:
print 'queueStream is non-empty'
if __name__ == '__main__':
try:
runner = RunStream()
runner.start()
flow = FlowController()
flow.start()
except KeyboardInterrupt:
print '\nGoodbye!'
编辑::::::::::::
感谢你目前的帮助。Queue 文档很好,自从 get() 函数块以来,它帮助我编写了更简洁的代码(酷!)。无论如何,它仍然没有解决我的问题,但是我在将 queueStream 实例传递给 FlowController 之前和之后打印了它,它们有两个不同的内存位置。这就是为什么我相信 FlowController 的队列中没有弹出任何内容。这是否意味着 Python 按值而不是按引用传递 queueStream?如果是这样,我该如何解决?
from stream import *
from textwrap import TextWrapper
from threading import Thread
from Queue import Queue
import time
class FlowController(Thread):
def __init__(self, queueStream):
Thread.__init__(self)
self.queueStream=queueStream
def run(self):
while True:
status = self.queueStream.get()
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
def addToQueue(status):
print 'adding tweets to the queue'
queueStream.put(status)
queueStream = Queue()
if __name__ == '__main__':
try:
runner = RunStream()
runner.start()
flow = FlowController(queueStream)
flow.start()
except KeyboardInterrupt:
print '\nGoodbye!'