python - 从函数返回一个值,而无需等待它每次在 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 。有没有更好的选择而不写入文件?
谢谢
解决方案
你可以简单地用一个全局变量来做到这一点
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")
推荐阅读
- wordpress - 使用 My Custom Functions 插件编辑我的 wordpress 网站的页脚版权信用后,我的网站已关闭
- java - 命名应用程序包是否有任何严格的规则
- bootstrap-4 - Angular Material TextArea 自动调整大小不适用于 bootstrap 4
- java - 是否需要在本地安装mysql才能在另一台计算机上保存和检索sql数据?
- c++ - C++中的嵌套结构
- jenkins - 如何在电子邮件中使用 Jenkins 发送最新附件?
- file - NiFi - TailFile - 多个文件
- php - laravel 5.5 电子邮件通知未更新内容
- java - 使用 DAO 模式对数据进行建模和访问
- python-2.7 - 两次启动同一个线程