1
wwqgtxx 2018-04-20 21:54:55 +08:00 via iPhone
一般都是用信号量去通知进程自己退出
|
2
Sylv 2018-04-20 21:59:23 +08:00 via iPhone 1
except KeyboardInterrupt
|
3
byteli 2018-04-20 22:00:49 +08:00
关键词 python 信号处理 SIGINT
|
4
Aliencn 2018-04-20 22:41:42 +08:00
数据量不大的话可以变量更改时在其他地方也写一份,比如用 log,redis 之类的
|
5
SingeeKing 2018-04-20 22:52:54 +08:00
except KeyboardInterrupt:
pass |
6
Pyjamas 2018-04-20 23:13:55 +08:00
```
import atexit def exit_handler(): global config with open('reservoir_simulate.config', 'w') as config_file: config_file.write(json.dumps(config, indent = 4)) print('Program finished! Current node = ' + str(config["reservoir"]["start_node"])) if __name__ == '__main__': atexit.register(exit_handler) ``` [Doing something before program exit]( https://stackoverflow.com/questions/3850261/doing-something-before-program-exit) |
7
Pyjamas 2018-04-20 23:18:03 +08:00
Sorry 打错了- -
``` import atexit def exit_handler(): ... if __name__ == '__main__': atexit.register(exit_handler) ``` |
8
dwjgwsm OP try...except 和 atexit 都不行,singal 倒是可以终止程序,但是不能注册函数,如果注册函数,则无法终止程序,处理函数也不会执行:
#main.py .......... def hander(a,b): print('.....test........') if __name__ == '__main__': import signal signal.signal(signal.SIGTERM,hander) #如果注册函数则无法终止程序,不注册则可以终止程序 from PyQt5.QtCore import QCoreApplication app = QCoreApplication(sys.argv) main = MainEngine() main.login() app.exec_() #a.py import signal import os os.kill(<pid>,signal.SIGTERM) |
9
guyskk0x0 2018-04-22 19:50:09 +08:00 via Android
@dwjgwsm signal hander 里要主动调用 sys.exit 退出。kill 信号有很多种,Unix 信号机制了解一下。
|
10
Pyjamas 2018-04-23 22:30:19 +08:00
atexit 为啥不行,我平时都用这个,就是 ctrl+c 或者 kill -INT $pid 杀死进程的时候,exit_handler()函数都会执行的
|
11
cortexm3 2018-04-24 15:17:24 +08:00
信号量
|
12
luoqize1 2018-04-24 15:47:12 +08:00
捕获 ctrl+c
|