You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python异步脚本报错RuntimeError: event loop is closed求助

邮件脚本运行时出现RuntimeError: event loop is closed错误的排查过程

我开发了一个邮件脚本,使用谷歌应用密钥获取邮箱访问权限,但运行时抛出RuntimeError: event loop is closed错误。

尝试的解决及测试过程

1. 单个行业处理版本

最初重构了main函数尝试解决,代码如下:

async def main():
    industry = 'resturaunts'
    async with aiohttp.ClientSession() as session:
        next_page_token = None
        companies = await process_industry(industry, session, next_page_token)
        for company in companies:
            await outreach_to_company(session, company,10)

但仅处理单个行业的版本仍返回该运行时错误。

2. 仅调用单个send_email函数版本

随后尝试仅调用单个邮件发送函数:

async def main():
    await send_email("tgjadore@gmail.com", 'Company')

该版本可正常运行,但无法实现脚本完整功能。

3. 多行业循环版本

之后尝试多行业循环版本:

async def main():
    industries = ['restaurants', 'barbers', 'cafes', 'gyms']

    async with aiohttp.ClientSession() as session:
        for industry in industries:
            next_page_token = None
            while True:
                companies = get_companies(industry, next_page_token)
                if not companies or 'places' not in companies:
                    print('Nothing to scrape')
                    break

                tasks = [outreach_to_company(session, company) for company in companies['places']]
                print(tasks)
                await asyncio.gather(*tasks)

                if 'nextPageToken' not in companies:
                    print('No nextPageToken')
                    break

                next_page_token = companies['nextPageToken']
                await asyncio.sleep(10)

该版本在打印Nothing to scrape后崩溃。

内容的提问来源于stack exchange,提问作者Jadore Thompson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 10:25:02