D
D
Dmitry Prilepsky2020-08-25 13:10:22
Python
Dmitry Prilepsky, 2020-08-25 13:10:22

How to call an async function from a normal function?

At once I will make a reservation that I faced asynchrony for the first time. I have telethon library functions (which works asynchronously). The main function looks like this:

class Main_telegram():
   async def main(self, url):
      channel = await client.get_entity(url) #берём нужный канал
      users = await dump_all_participants(channel) #берём людей, находящихся на канале
      return users

And I need to call the main function of this class in another class. Here is how I implemented it:
class Telegram:
    def __init__(self) -> None:
        self.cv_telegram = Main_telegram()

    def working(self, list_url):
       list_cv_in_groups = []
       url_groups = list_url
       for url_group in url_groups:
           list_cv_telegram = self.cv_telegram.main(url_group)
           list_cv_in_groups.append(list_cv_telegram)
            
cv_telegram = Telegram()

But when I call the main function, the program does not enter this function in another class, but creates a coroutine object MainTelegram.main . I read the documentation on this object, but did not understand how to work with it. From this and my question. How do I call an async function from a normal function, and is it even possible?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
Gennady S, 2020-08-25
@HartX

You'll have to go async from the root, any async is followed by an await (and vice versa):

import asyncio

async def main():
    await ... # вызов библиотек

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main()) # передайте точку входа
    finally:
        # действия на выходе, если требуются
        pass

Yes, it is worth understanding the work of asyncio through documentation or publication guides.
PS why Main_telegram and not MainTelegram ? Take a look at https://www.python.org/dev/peps/pep-0008/#class-names , it makes sense to follow code style approaches.

D
Dr. Bacon, 2020-08-25
@bacon

And let's first you open the docks and read https://docs.python.org/3/library/asyncio.html

S
Sergey Gornostaev, 2020-08-25
@sergey-gornostaev

Either use the synchronous library, or read the asyncio documentation, otherwise you will be in for a lot of surprises.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question