繁体   English   中英

Python 线程与流作为 for 循环?

[英]Python threading with streaming as for loop?

我的流算法看起来像这样

queue = stream.request
for item in queue:
    if item == what_i_am_looking_for:
        output=open_webpage()
        send_message(output)

for 循环和 open_webpage() 都涉及等待 i/o,无论是来自我正在等待的流还是我想要加载的网页。 问题是打开一个网页可能需要很多时间,导致我在我的流队列中落后。

这对我来说似乎是线程的完美候选者,我最近了解到。 但是我该如何实施呢? 我尝试的是制作看起来像这样的东西:

queue = stream.request
for item in queue:
    if item == what_i_am_looking_for:
        found_item_thread=Thread(target=open_webpage_and_send)
        found_item_thread.start
        found_item_thread.join

但它不像我想要的那样工作。 我想要发生的是程序不断加载队列中的新流项目。 然后,当找到我要查找的项目时,它会继续加载流的队列,但作为线程同时加载网页。

编辑:@abdusco 所以使用 ThreadPoolExecutor,我的伪代码会像这样吗?

def stream():
    queue = stream.request
    for item in queue:
        if item == what_i_am_looking_for:
            open_webpage=executor.submit(open_webpage)

def main():
    ThreadPoolExecutor as executor:
    stream=executor.submit(stream)

您可能希望使用 asyncio 并创建一个后台任务,如下所示 -

import asyncio

async def my_task():
    output=open_webpage()
    await send_message(output)

queue = stream.request 
for item in queue:
    if item == what_i_am_looking_for:
        #Task will run in the background, for loop will keep running
        asyncio.create_task(my_task())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM