簡體   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