我刚刚开始尝试使用 AsyncPraw Reddit API 包装器创建一个机器人。我复制粘贴了文档中的代码示例,但我无法在没有警告的情况下运行它。
尝试执行此代码:
import asyncpraw
import asyncio
import auth
from time import sleep
async def amain():
reddit = asyncpraw.Reddit(
client_id=auth.CLIENT_ID,
client_secret=auth.CLIENT_SECRET,
user_agent="Example bot",
password=auth.PASSWORD,
username=auth.USERNAME,
ratelimit_seconds=700
)
print(reddit.read_only)
# Output: True
# continued from code above
subreddit = await reddit.subreddit("askreddit")
async for submission in subreddit.top(limit=10):
print(submission.title)
asyncio.run(amain())
一切正常,提交标题被打印,但随后,这种情况发生了:
> Unclosed client session client_session: <aiohttp.client.ClientSession
> object at 0x000001D53CA8D6C0> Unclosed connector connections:
> ['[(<aiohttp.client_proto.ResponseHandler object at
> 0x000001D53C246FE0>, 116575.906)]'] connector:
> <aiohttp.connector.TCPConnector object at 0x000001D53CA8D7E0> Fatal
> error on SSL transport protocol: <asyncio.sslproto.SSLProtocol object
> at 0x000001D53CA8EB30> transport: <_ProactorSocketTransport fd=-1
> read=<_OverlappedFuture cancelled>>
...
> RuntimeError: Event loop is closed
尝试通过将
asyncio.run(amain())
替换为: 来修复
loop = asyncio.get_event_loop()
loop.run_until_complete(amain())
这修复了
RuntimeError: Event loop is closed
,但是 Unclosed client session client_session: <aiohttp.client.ClientSession
。其后的所有内容都保留下来。
最重要的是,现在我得到了
DeprecationWarning:当前没有事件循环 循环 = asyncio.get_event_loop()
我自己找到了答案。我只需要添加
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
之前
asyncio.run(amain())
它将正常工作,不会出现错误或警告。