在KeyboardInterrupt上关闭asyncio循环-运行停止例程

时间:2019-01-26 22:20:25

标签: python python-asyncio python-3.7

我正在使用python创建一个脚本,该脚本同时运行并与某些进程进行交互。为此,我使用asyncio来实现这种并行性。主要问题是发生KeyboardInterrupt或SIGINT时如何运行另一个清理例程。

这是我编写的示例代码,用于显示问题:

import asyncio
import logging
import signal
from time import sleep


class Process:
    async def start(self, arguments):
        self._process = await asyncio.create_subprocess_exec("/bin/bash", *arguments)

        return await self._process.wait()

    async def stop(self):
        self._process.terminate()


class BackgroundTask:

    async def start(self):
        # Very important process which needs to run while process 2 is running
        self._process1 = Process()
        self._process1_task = asyncio.create_task(self._process1.start(["-c", "sleep 100"]))

        self._process2 = Process()
        self._process2_task = asyncio.create_task(self._process2.start(["-c", "sleep 50"]))

        await asyncio.wait([self._process1_task, self._process2_task], return_when=asyncio.ALL_COMPLETED)

    async def stop(self):
        # Stop process
        await self._process1.stop()

        # Call a cleanup process which cleans up process 1
        cleanup_process = Process()
        await cleanup_process.start(["-c", "sleep 10"])

        # After that we can stop our second process
        await self._process2.stop()


backgroundTask = BackgroundTask()


async def main():
    await asyncio.create_task(backgroundTask.start())


logging.basicConfig(level=logging.DEBUG)
asyncio.run(main(), debug=True)

此代码创建一个后台任务,该任务启动两个进程(在本示例中为两个bash sleep命令),并等待它们完成。这可以正常工作,并且两个命令都并行运行。

主要问题是停止例程。当程序收到SIGINT或KeyboardInterrupt时,我想运行stop方法,该方法首先停止process1,然后启动清理方法,然后再停止process2。这是必需的,因为清理命令取决于process2。

我尝试过的方法(而不是asyncio.run()和async main):

def main():
    try:
        asyncio.get_event_loop().run_until_complete(backgroundTask.start())
    except KeyboardInterrupt:
        asyncio.get_event_loop().run_until_complete(backgroundTask.stop())

main()

这当然不能按预期工作,因为一旦出现KeyboardInterrupt异常,就会取消backgroundTask.start任务,并在主循环中启动backgroundTask.stop,因此我的进程将被取消并且无法停止正确地

有没有办法在不取消当前主循环的情况下检测到KeyboardInterrupt并运行我的backgroundTask.stop方法?

1 个答案:

答案 0 :(得分:0)

您想添加一个信号处理程序,如文档中的 example 所示:

import asyncio
import functools
import os
import signal

def ask_exit(signame, loop):
    print("got signal %s: exit" % signame)
    loop.stop()

async def main():
    loop = asyncio.get_running_loop()

    for signame in {'SIGINT', 'SIGTERM'}:
        loop.add_signal_handler(
            getattr(signal, signame),
            functools.partial(ask_exit, signame, loop))

    await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")

asyncio.run(main())

不过,这是一个过于复杂/过时的示例,请考虑更像这样(您的协程代码位于 asyncio.sleep 调用所在的位置):

import asyncio
from signal import SIGINT, SIGTERM
    

async def main():
    loop = asyncio.get_running_loop()
    for signal_enum in [SIGINT, SIGTERM]:
        loop.add_signal_handler(signal_enum, loop.stop)

    await asyncio.sleep(3600) # Your code here


asyncio.run(main())

此时 Ctrl + C 将中断循环并引发 RuntimeError,您可以通过将 asyncio.run 调用放在 try/except 块中来捕获它像这样:

try:
    asyncio.run(main())
except RuntimeError as exc:
    expected_msg = "Event loop stopped before Future completed."
    if exc.args and exc.args[0] == expected_msg:
        print("Bye")
    else:
        raise

虽然这不是很令人满意(如果其他原因导致了同样的错误怎么办?),所以我更愿意提出一个明显的错误。此外,如果您在命令行上退出,正确的做法是返回正确的退出代码(实际上,示例中的代码仅使用名称,但它实际上是带有该数字的 IntEnum退出代码!)

import asyncio
from functools import partial
from signal import SIGINT, SIGTERM
from sys import stderr

class SignalHaltError(SystemExit):
    def __init__(self, signal_enum):
        self.signal_enum = signal_enum
        print(repr(self), file=stderr)
        super().__init__(self.exit_code)

    @property
    def exit_code(self):
        return self.signal_enum.value

    def __repr__(self):
        return f"\nExitted due to {self.signal_enum.name}"

def immediate_exit(signal_enum, loop):
    loop.stop()
    raise SignalHaltError(signal_enum=signal_enum)

async def main():
    loop = asyncio.get_running_loop()

    for signal_enum in [SIGINT, SIGTERM]:
        exit_func = partial(immediate_exit, signal_enum=signal_enum, loop=loop)
        loop.add_signal_handler(signal_enum, exit_func)

    await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")

asyncio.run(main())

当 Ctrl + C 退出时:

python cancelling_original.py

Event loop running for 1 hour, press Ctrl+C to interrupt.
^C
Exitted due to SIGINT
echo $?

2

现在有一些代码我很乐意提供! :^)

附言这是带有类型注释的:

from __future__ import annotations

import asyncio
from asyncio.events import AbstractEventLoop
from functools import partial
from signal import Signals, SIGINT, SIGTERM
from sys import stderr
from typing import Coroutine

class SignalHaltError(SystemExit):
    def __init__(self, signal_enum: Signals):
        self.signal_enum = signal_enum
        print(repr(self), file=stderr)
        super().__init__(self.exit_code)

    @property
    def exit_code(self) -> int:
        return self.signal_enum.value

    def __repr__(self) -> str:
        return f"\nExitted due to {self.signal_enum.name}"

def immediate_exit(signal_enum: Signals, loop: AbstractEventLoop) -> None:
    loop.stop()
    raise SignalHaltError(signal_enum=signal_enum)

async def main() -> Coroutine:
    loop = asyncio.get_running_loop()

    for signal_enum in [SIGINT, SIGTERM]:
        exit_func = partial(immediate_exit, signal_enum=signal_enum, loop=loop)
        loop.add_signal_handler(signal_enum, exit_func)

    return await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")

asyncio.run(main())

这里自定义异常的好处是你可以专门捕获它,避免回溯被转储到屏幕

try:
    asyncio.run(main())
except SignalHaltError as exc:
    # log.debug(exc)
    pass
else:
    raise