简体   繁体   中英

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. 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?

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.

Make sure your long operation function is defined 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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