首页 > 解决方案 > 从函数返回一个值,而无需等待它每次在 Python 中完成

问题描述

我已经阅读了多个论坛主题,但仍然想问一个具体问题。也许有人可以提出更好的建议。

所以,有一个迭代列表的主循环。列表本身是使用一个函数生成的,该函数在 30-50 秒内返回它(在将项目附加到它之后)。在每次调用时无需等待生成最近的完整列表的最佳方法是什么?

这是一个简单的例子:

def check_list():
    list1 = [1, 2, 3, 4]
    list_upd = []

    for i in list1:
        if 4 > i > 1:
            list_upd.append(i)
    return list_upd # return the updated list

while True:
    print("start") # we wait for 30 sec for the list to be generated

    for i in check_list():
         print(i)
    
    print("finish") # iterating through the list is completed

这个想法是无论何时调用函数都能够获取更新的列表,而无需每次都等待它完成。获取最新生成的列表并不重要(之前的列表也可以)。一种可能的选择是将其写入文件,然后从那里读取并在后台更新。也应该使用 asyncio 。有没有更好的选择而不写入文件?

谢谢

标签: python

解决方案


你可以简单地用一个全局变量来做到这一点

def check_list():
    global list_upd    
    if 'list_upd' in globals():
        return list_upd 
    list1 = [1, 2, 3, 4]
    list_upd = []

    for i in list1:
        if 4 > i > 1:
            list_upd.append(i)
    print("new list")
    return list_upd # return the updated list

while True:
    print("start") # we wait for 30 sec for the list to be generated

    for i in check_list():
         print(i)
    
    print("finish") # iterating through the list is completed 

在使用线程澄清问题后编辑工作解决方案。

import threading
import time    
def check_list():
    global list_upd    
    if 'list_upd' in globals():
        return list_upd 
    list1 = [1, 2, 3, 4]
    list_upd = []
    for i in list1:
        if 4 > i > 1:
            list_upd.append(i)
    print("new list")
    return list_upd
def thread_function():
    while True:
        global list_upd    
        list1 = [1, 2, 3, 4]
        list_upd_2 = []
        for i in list1:
            if 4 > i > 1:
                list_upd_2.append(i)
        print("new list")
        list_upd=list_upd_2
        time.sleep(1)
   
x = threading.Thread(target=thread_function)
x.start()   
while True:
    print("start") # we wait for 30 sec for the list to be generated
    for i in check_list():
         print(i)
    time.sleep(1)
    print("finish")

推荐阅读