首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >'ListingGenerator‘对象不能使用ASYNCPRAW进行迭代

'ListingGenerator‘对象不能使用ASYNCPRAW进行迭代
EN

Stack Overflow用户
提问于 2021-02-11 19:38:01
回答 1查看 886关注 0票数 0

我想从一个删减员那里得到模因。问题是,当我尝试使用subreddit('memes')方法获取模因时,该方法返回一个不可迭代的‘ListingGenerator’对象。

我想知道是否有任何方法将其转换为一个可迭代对象或任何其他方法来使用ASYNCPRAW从reddit获取模因。

以下是功能:

代码语言:javascript
复制
    async def meme(self, ctx):
    subreddit = await  reddit.subreddit('memes')
    print(type(subreddit))
    all_subs = []
    print(subreddit.hot(limit=50))
    for submission in subreddit.hot(limit=50):
        all_subs.append(submission)
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    embed = discord.Embed(title=name)
    embed.set_image(url=url)
    await ctx.send(embed=embed)

这是我得到的错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\ansel\PycharmProjects\Transfer News\cogs\meme.py", line 48, in meme
    for submission in subreddit.hot(limit=50):
TypeError: 'ListingGenerator' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'ListingGenerator' object is not iterable
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-11 21:53:06

meme命令中,您使用一个for循环来迭代返回的ListingGenerator,这是一个异步源。在这种情况下,您需要使用async for循环来迭代异步源。

使用普通的for循环,除非尝试阻塞事件循环,否则不允许在异步源上迭代,因为for调用__next__作为阻塞函数,而不等待其结果。

关于如何在示例中迭代返回的ListingGenerators,有一些文档

参考文献:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66161657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档