Warm tip: This article is reproduced from serverfault.com, please click

python-'ListingGenerator' 对象不能使用 ASYNCPRAW 迭代

(python - 'ListingGenerator' object is not iterable using ASYNCPRAW)

发布于 2021-02-11 19:38:01

我想从 subreddit 中获取模因。问题是当我尝试使用该方法获取模因时,subreddit('memes')该方法返回一个不可迭代的“ListingGenerator”对象。

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

这是函数:

    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)

这是我得到的错误:

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
Questioner
Ansel D'souza
Viewed
0
Shunya 2021-02-12 05:53:06

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

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

有一些例子,如何遍历返回ListingGeneratorsAPRAW文档

参考: