如何在 Python 中捕获 SIGINT

问题描述

晚上!

目前我正在玩 pm2 并且目前我正在尝试执行一个函数或尝试/除了抓住停止(当我使用 pm2 stop 时)。

我试图通过执行以下操作来捕获签名:

from signal import signal,SIGINT
from sys import exit

def handler(signal_received,frame):
    # Handle any cleanup here
    print('SIGINT or CTRL-C detected. Exiting gracefully')
    exit(0)

if __name__ == '__main__':
    # Tell Python to run the handler() function when SIGINT is recieved
    signal(SIGINT,handler)

    print('Running. Press CTRL-C to exit.')
    while True:
        # Do nothing and hog cpu forever until SIGINT received.
        pass

然而,每当我使用 pm2 stop 停止脚本时,它似乎永远不会捕获信号。在 pm2 日志中是以下代码

PM2        | 2021-03-31T22:00:41: PM2 log: App [test3:1] starting in -fork mode-
PM2        | 2021-03-31T22:00:41: PM2 log: App [test3:1] online
PM2        | 2021-03-31T22:00:47: PM2 log: Stopping app:test3 id:1
PM2        | 2021-03-31T22:00:47: PM2 log: App [test3:1] exited with code [1] via signal [SIGINT]
PM2        | 2021-03-31T22:00:47: PM2 log: pid=1564 msg=process killed

出于某种原因,kill 这个词对我来说听起来更像是 SIGKILL 而不是 SIGINT,但它确实抛出了我所看到的信号,然后将其杀死。

我的问题是,如何在使用 pm2 stop 命令实际关闭脚本之前捕获它?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)