python - 不断检查列表并在列表中有项目时执行某些操作

标签 python list queue iteration gevent

我有一个全局列表,其中不断添加项目(来自网络客户端):

mylist = []
def additem(uuid,work):
    mylist.append(uuid,work)

还有一个应该检查列表的函数,如果有项目就继续执行:

def proceeditems():

  while True:
    itemdone = []
    if len(mylist) > 0:
     for item in mylist:
       try:
          #This can go wrong and than need to be done again 
          result = gevent.spawn(somework(item))
          #result returns the uuid
          itemdone.append(result.value)
       except:
          pass
    for item in itemdone:
        mylist[:] = [value for value in mylist if value[0]!=item]

所以我希望你现在知道我想做什么,但我认为无限循环似乎不是正确的解决方案。

最佳答案

在这种情况下,您必须使用多线程或多处理(取决于网络客户端是否在不同线程或不同进程上运行。

无论哪种情况,您都应该使用 Queue管理传入的数据,然后存储到 itemdone 中。

您可以这样定义队列:

my_queue = queue.Queue() # or multiprocessing.Queue()

然后你应该在参数中包含队列(或者如果你使用线程,你可以使用全局队列,就像你所做的那样)

def additem(uuid,work,the_queue):
    the_queue.put((uuid,word)) # Queue in a tuple containing the data

def proceeditems(the_queue):
    while True:
        item = the_queue.get() # This will block until something is inside the queue
        try:
            result = somework(item)
            itemdone.append(result)
        except:
            the_queue.put(item) # If failed, put back to queue for retry.
        # You don't need the last two lines

要停止整个过程,可以让additem函数插入特殊 token ,proceeditems在收到特殊 token 后,将退出循环。

关于python - 不断检查列表并在列表中有项目时执行某些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20231594/

相关文章:

Python:如何使用 string.translate() 替换引号? (用于 "slug"创建)

android - pygame - 将对象链接到鼠标事件

python - 像在 Postman 中一样在 Python 中获取访问 token

r - 在列表中查找对象的位置编号

c# - 如何在 C# 中创建通用列表并使用 Select SQL 查询进行填充

javascript - jQuery 队列,它是如何工作的?

java - 向双端队列添加和删除元素

c# - 在队列中查找特定操作的索引

python - pytesseract Windows错误: [Error 5] Access is denied

python - 将列表粘贴到 Excel 文件