如何正确处理用户在python中发送的多个SIGINT

时间:2018-10-09 07:49:06

标签: python multithreading signals

我有一个使用多线程的python程序,并且我想处理用户发送的意外信号,以便正常退出执行。

例如,在运行期间,如果我收到“ Cntrl + C”,我想指示所有子线程关闭(通过事件),一旦线程完成拆除,则我将ll让程序退出。

我基本上发现使用以下方法可以解决此问题:

scripts = soup.find_all('script')
your_script = [script for script in scripts if 'tmxSessionId' in str(script)][0]
script_tag = your_script
soup = BeautifulSoup(script_tag, 'lxml')
script = soup.find_all('script')[0]
data = re.findall("{.*?}", script.text)[0]

print(json.loads(data)['tmxSessionId'])

但是我注意到,如果我按下多个“ Cntrl + c”,那么“ MY-METHOD”将一遍又一遍地运行,这是不好的,因为在这种情况下,我无法取得任何进展线程。

我想知道,处理这样的情况的最佳方法是什么:在短时间内用户反复发送SIGINT。防止MY-METHOD从头开始一遍又一遍的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

经过几次尝试,我发现以下内容对我有用:

#Define the initial signal handler
signal.signal(signal.SIGINT, signal_handler)

def signal_handler(sig,frame):
    #Define a new handler to ignore any SIGINT
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    < handler code afterwards >
相关问题