F
F
freakssha2019-12-08 20:14:54
Python
freakssha, 2019-12-08 20:14:54

How to implement an async function with asyncio in my case?

The goal is to create a document not after closing the program, as it happens now, but while it is running.
The "first" function just needs to call the asynchronous "second" which will create the docx.

def first(self, event):
    loop = asyncio.get_event_loop()
    loop.run(self.second())

async def second(self):
    document = Document()
    document.save('test.docx')

I'm sure the problem is in the "first" function, in how it calls "second".
I'm working on an old project that I don't have time to fix; inside there are a lot of errors in basic things, so the browser did not help - you need something specifically for the situation. Despite this, please tell me how to solve the problem.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ihor Peresunko, 2019-12-12
@freakssha

Why doesn't it work specifically? There are mistakes?
Move the start of the loop out of the function. Here is a working example.

import asyncio


class Document:
    async def save(self, name):
        await asyncio.sleep(1)
        print(f'Document "{name}" has saved')


async def first():
    name = "test_document.doc"
    print("Run first function")
    await second(name)


async def second(name):
    await Document().save(name)


asyncio.run(first())

From the first function, you can asynchronously save both one document and several (via await asyncio.gather).
async def first():
    print("Run first function")
    await asyncio.gather(
        second('doc_1'),
        second('doc_2'),
        second('doc_3'),
    )

The implementation of the Document class is not clear from the code, but I would advise you to make saving also non-blocking. For example, you can use aiofile to asynchronously save documents to disk.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question