【问题标题】:Python threading with streaming as for loop?带有流的Python线程作为for循环?
【发布时间】:2021-06-29 22:57:41
【问题描述】:

我的流媒体算法看起来像这样

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)

【问题讨论】:

  • 你可以让你的 open_webpage() 函数异步而不是等待它然后你输出 = ....
  • @m0bi5 我对异步函数一无所知。你能举例说明它是如何实现的吗?它像线程一样工作吗?
  • 逻辑上和线程很相似,看看这个-realpython.com/async-io-python
  • 查看 ThreadPoolExecutor。 docs.python.org/3/library/…
  • @m0bi5 好吧,在看了一点 asynchio 之后,我想我基本上了解它是如何工作的。您是否建议我将 output=... 行更改为任务?如 output=asynchio.create_task(open_webpage())?使用 open_webpage 函数和此代码之前的函数是“异步”?

标签: python multithreading web-scraping streaming python-multithreading


【解决方案1】:

您可能希望使用 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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2017-06-13
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2018-11-07
    相关资源
    最近更新 更多