如何从bash脚本向Python发送SIGINT? [英] How to send a SIGINT to Python from a bash script?

查看:99
本文介绍了如何从bash脚本向Python发送SIGINT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从bash脚本启动一个后台Python作业,然后使用SIGINT优雅地杀死它.从shell可以正常工作,但是我似乎无法在脚本中使用它.

I want to launch a background Python job from a bash script and then gracefully kill it with SIGINT. This works fine from the shell, but I can't seem to get it to work in a script.

loop.py:

#! /usr/bin/env python
if __name__ == "__main__":
    try:
        print 'starting loop'
        while True:
            pass
    except KeyboardInterrupt:
        print 'quitting loop'

从外壳我可以中断它:

$ python loop.py &
[1] 15420
starting loop
$ kill -SIGINT 15420
quitting loop
[1]+  Done                    python loop.py

kill.sh:

#! /bin/bash
python loop.py &
PID=$!
echo "sending SIGINT to process $PID"
kill -SIGINT $PID

但是从脚本中我不能:

$ ./kill.sh 
starting loop
sending SIGINT to process 15452
$ ps ax | grep loop.py | grep -v grep
15452 pts/3    R      0:08 python loop.py

而且,如果它是从脚本启动的,我将无法再从外壳中将其杀死:

And, if it's been launched from a script I can no longer kill it from the shell:

$ kill -SIGINT 15452
$ ps ax | grep loop.py | grep -v grep
15452 pts/3    R      0:34 python loop.py

我假设我缺少bash作业控制的一些要点.

I'm assuming I'm missing some fine point of bash job control.

推荐答案

您没有注册信号处理程序.请尝试以下方法.它似乎工作相当可靠.我认为罕见的例外是当它在Python注册脚本的处理程序之前捕获到信号时.请注意,仅在用户按下中断键时"才应提出KeyboardInterrupt.我认为它完全适用于显式(例如通过kill)SIGINT的事实是实施的偶然情况.

You're not registering a signal handler. Try the below. It seems to work fairly reliably. I think the rare exception is when it catches the signal before Python registers the script's handler. Note that KeyboardInterrupt is only supposed to be raised, "when the user hits the interrupt key". I think the fact that it works for a explicit (e.g. via kill) SIGINT at all is an accident of implementation.

import signal

def quit_gracefully(*args):
    print 'quitting loop'
    exit(0);

if __name__ == "__main__":
    signal.signal(signal.SIGINT, quit_gracefully)

    try:
        print 'starting loop'
        while True:
            pass
    except KeyboardInterrupt:
        quit_gracefully()

这篇关于如何从bash脚本向Python发送SIGINT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆