gpt4 book ai didi

python - 在python中定期和异步地获取值

转载 作者:行者123 更新时间:2023-12-03 13:09:23 26 4
gpt4 key购买 nike

我有以下python脚本。我想在异步运行的每10秒后重复执行timer函数。我查看了post1post2,但它们没有返回任何值。

import threading
def timer(bar, baz):
print 'hello {0}'.format(bar)
return 'foo' + baz

from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=1)

async_result = pool.apply_async(timer, ('world', 'foo'))

return_val = async_result.get()
print return_val

主线程仍在执行其他工作时,是否有办法在每t个时间间隔后获取值?

最佳答案

使用您链接到的内容的一种方法:

from threading import Timer
from multiprocessing.pool import ThreadPool
from time import sleep

def getLast():
global got
Timer(10,getLast).start()
got = async_result.get()

def action(bar, baz):
print 'hello {0}'.format(bar)
return 'foo ' + baz

pool = ThreadPool(processes=1)
async_result = pool.apply_async(action, ('world', 'foo'))
Timer(10,getLast).start()

string = 'a'
while True:
got = None
while got is None:
sleep(2)
print 'Doing stuff'
print 'Got:',got
async_result = pool.apply_async(action, ('world', 'foo '+string))
string +='a'
got = None

内部while模仿主线程“做事”,每隔10秒钟,您应该从async_result中获得一个新结果,并开始新的非阻塞运行。外循环只是保持主线程运行。

关于python - 在python中定期和异步地获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40548470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com