Answer the question
In order to leave comments, you need to log in
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')
Answer the question
In order to leave comments, you need to log in
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())
async def first():
print("Run first function")
await asyncio.gather(
second('doc_1'),
second('doc_2'),
second('doc_3'),
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question