从异步函数返回列表 [英] Return a list from asyncio function

查看:69
本文介绍了从异步函数返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码.我知道在某处可能是错误的,但是在运行后可以返回列表电报列表怎么办?只是想可以全局访问列表项?

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()

推荐答案

您在 main 协程中缺少 await .已更正,看起来像这样:

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

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

这篇关于从异步函数返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆