gpt4 book ai didi

python - Python3.7 中的触发、遗忘和返回值

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:50 26 4
gpt4 key购买 nike

我有以下场景:我有一个 python 服务器,在收到请求后,需要解析一些信息,尽快将结果返回给用户,然后自行清理。我尝试使用以下逻辑来设计它:

Consumer: *==*   (wait for result)   *====(continue running)=====...
\ / return
Producer: *======(prase)====*=*
\
Cleanup: *==========*

我一直在尝试使用异步任务和协程来使这种情况无济于事。我尝试的所有操作都以生产者在返回之前等待清理完成或返回杀死清理而告终。理论上我可以让消费者在向用户显示结果后调用清理,但我拒绝相信 Python 不知道如何“即发即弃”并返回。

例如,这段代码:

import asyncio

async def Slowpoke():
print("I see you shiver with antici...")
await asyncio.sleep(3)
print("...pation!")

async def main():
task = asyncio.create_task(Slowpoke())
return "Hi!"

if __name__ == "__main__":
print(asyncio.run(main()))
while True:
pass

返回:

I see you shiver with antici...
Hi!

永远不会...pation

我错过了什么?

最佳答案

我设法使用线程而不是 asyncio 让它工作:

import threading
import time

def Slowpoke():
print("I see you shiver with antici...")
time.sleep(3)
print("...pation")

def Rocky():
t = threading.Thread(name="thread", target=Slowpoke)
t.setDaemon(True)
t.start()
time.sleep(1)
return "HI!"

if __name__ == "__main__":
print(Rocky())
while True:
time.sleep(1)

关于python - Python3.7 中的触发、遗忘和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57407124/

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