简体   繁体   English

如何暂停一个 function 的执行以在 Python 中执行另一个 function:

[英]How to pause an execution of one function to do another function in Python:

I have a telgram bot that handles with the text messages and documents and the function that handles with documents will do long operations with the documents.我有一个处理文本消息和文档的电报机器人,处理文档的 function 将对文档进行长时间的操作。 This causes the next problem: until the job with file is done, the bot won't continue handling text messages.这导致了下一个问题:在文件工作完成之前,机器人不会继续处理文本消息。 Is there a way to "pause" the execution of file_handler function to send a message?有没有办法“暂停”file_handler function 的执行以发送消息?

dp = Dispatcher(bot)
@dp.message_handler(commands=["start"])
async def messages(mes:types.Message):
    if mes == "Hi":
        await bot.send_message(chat_id=mes.chat.id,text="Hi")
    if mes.text=="/start":
        await bot.send_document(mes.from_user.id,document=input_file.InputFile("c.pdf"))

import time
@dp.message_handler(content_types=ContentTypes.DOCUMENT)
async def doc_handler(message:types.Message):
    if document := message.document:
        await document.download(
            destination_file="file.pdf",
        )
        await bot.send_message(chat_id=message.chat.id, text="got file")
        do_with_file("file.pdf")

You can not "pause" a function, but you can use asyncio to run functions concurrently as tasks.您不能“暂停” function,但您可以使用asyncio将函数作为任务同时运行。

Make sure your long operation function is defined async :确保您的长时间操作 function 定义为async

async def do_with_file(file_name: string):
    ...

Launch it as task :将其作为任务启动:

@dp.message_handler(content_types=ContentTypes.DOCUMENT)
async def doc_handler(message:types.Message):
    if document := message.document:
        await document.download(
            destination_file="file.pdf",
        )
        await bot.send_message(chat_id=message.chat.id, text="got file")
        asyncio.create_task(do_with_file("file.pdf"))

Also make sure you create a unique file name for every download so that if one file is still processing while another one is downloading they don't overwrite each other.还要确保为每次下载创建一个唯一的文件名,这样如果一个文件仍在处理而另一个文件正在下载,它们不会相互覆盖。

You can use the tempfile module for this, or just append the exact time to the file name.您可以为此使用tempfile模块,或者只是 append 文件名的确切时间。

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

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