简体   繁体   中英

Return a list from asyncio function

I have the following code from below. I know that probably is wrong somewhere, but how it must be to can return the list telegramlist after it is run? Just want to can access list items globally?

telegramlist = []
telegramchannellist = ['TelethonChat-anti-kyle']


async def telegram_method():
    api_id = '*'
    api_hash = '*'

    client = TelegramClient('trendingsesion', api_id, api_hash)
    client.start()

    telegramdict = {}
    for ch in telegramchannellist:
        channel_username = ch
        channel_entity = client.get_entity(channel_username)
        posts = client(GetHistoryRequest(
            peer=channel_entity,
            limit=1,
            offset_date=None,
            offset_id=0,
            max_id=0,
            min_id=0,
            add_offset=0,
            hash=0))
        telegramdict[ch] = posts.messages # here if i write .messages shows a weird error, he want to be only posts
    telegramlist = list(telegramdict.values())
    return telegramlist

shuffle(telegramchannellist)
if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    telegramlistt = loop.run_until_complete(asyncio.gather(telegram_method()))
    loop.close()

You are missing an await in your main coroutine. Corrected, it would look like this:

async def main():
    telegramlist = await telegram_method()
    return telegramlist

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