0

我目前正在探索 python 中的 async/await。

我想启动 Pyrogram,然后运行 ​​cronjob 函数。我创建了这段代码:

import asyncio
from pyrogram import Client, Filters, MessageHandler
import time

app = Client("pihome")

async def cronjob():
    print("Cronjob started")
    while True:
        #print(f"time is {time.strftime('%X')}")
        print(int(time.time()))
        if int(time.strftime('%S')) == 10:
            print("SECONDO 10") # Change this with checks in future

        await asyncio.sleep(1)

async def main():
    print(f"Starting {app.session_name}...\n")
    # Pyrogram
    await app.start()
    print("Pyrogram started")

    # Cronjob
    loop = asyncio.new_event_loop()
    loop.run_until_complete(loop.create_task(await cronjob()))
    print("\nDone")

    await Client.idle()
    await app.stop()

    print(f"\nStopping {app.session_name}...")

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main())

但是当我想用 Ctrl+C 停止它时,它给了我这个回溯:

^CTraceback (most recent call last):
  File "pihome.py", line 39, in <module>
    asyncio.get_event_loop().run_until_complete(main())
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 603, in run_until_complete
    self.run_forever()
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
    self._run_once()
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 1823, in _run_once
    event_list = self._selector.select(timeout)
  File "/usr/local/lib/python3.8/selectors.py", line 468, in select
    fd_event_list = self._selector.poll(timeout, max_ev)
KeyboardInterrupt

我该如何解决?此外,try/except 块似乎不起作用

4

1 回答 1

1
  1. 要运行应用程序,最好使用asyncio.run(main())。在我看来,它更清楚。

  2. 替换循环=异步。new_event_loop() by loop = asyncio. 获取事件循环()。因为在 asyncio.get_event_loop().run_until_complete(main()) 之后使用 asyncio.new_event_loop() 您会在主线程中创建第二个事件循环,这是被禁止的。每个线程只允许一个事件循环!

  3. 从此行中删除等待:

    loop.run_until_complete(loop.create_task(等待 cronjob()))

因为create_task需要Coroutine作为第一个参数,但你传递它 None

于 2020-04-07T22:18:34.930 回答