我构建了一个电子邮件脚本,利用来自谷歌的用户应用程序密钥来访问他们的电子邮件。但是,当我运行脚本时,我收到错误“运行时错误:事件循环已关闭”。
在最初发现时,我决定重建该功能,因为我是构建它的人,所以也许我只是做错了什么:
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)
以上是我尝试使其在单一行业项目上运行。这又返回了运行时错误。然后我尝试了另一种解决方案,其中使用了单个函数 send_email:
async def main():
await send_email("[email protected]", 'Company')
这确实有效,但这并不是脚本的全部功能。然后我尝试了:
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)
在没有任何内容可抓取的所有打印语句之后崩溃。
这里是完整的脚本,以防它对任何事情有帮助(mail.py):https://github.com/JadoreThompson/Email-Outreach-Bot/tree/development
为了解决这个问题,我不确定这是否在所有应用程序中都很常见,但它对我有用。设置事件循环策略,该策略将创建一个新的事件循环并设置当前的事件循环:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())