关机钩

扫码查看
本文介绍了关机钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道python是否能够运行关闭钩子。


例如你设置一个方法在python进程关闭时运行

down,就像它收到了一个kill信号?


基本上寻找类似下面java代码的效果。

Runtime.getRuntime()。addShutdownHook(新主题(本));

Does any one know if python has the ability to run a shutdown hook.

For example you set a method to run when the python process is shutting
down, like it recieved a kill signal?

Basically looking for an effect like the following java code.
Runtime.getRuntime().addShutdownHook(new Thread(this));

推荐答案




当Python运行时系统要退出时,它引发了一个SystemExit

异常。


在代码的顶层捕获异常,并做任何你想要的

。 (在某些时候实际退出可能是礼貌的,

当然.sys.exit(exitcode)会这样做 - 引发另一个SystemExit

异常。)


-

\我今天放轻松了。我整天躺在我的| b / b $ \内衣里。 ......虽然在很多地方被踢了出来,但是。

_o__)。 - Bug-Eyed Earl,_Red Meat_ |

Ben Finney



When the Python runtime system wants to exit, it raises a SystemExit
exception.

Catch that exception at the top level of your code, and do whatever
you like. (It might be polite to actually exit at some point, of
course. sys.exit(exitcode) will do so -- raising another SystemExit
exception.)

--
\ "I took it easy today. I just pretty much layed around in my |
`\ underwear all day. ... Got kicked out of quite a few places, |
_o__) though." -- Bug-Eyed Earl, _Red Meat_ |
Ben Finney





当Python运行时系统要退出时,它会引发SystemExit
异常。

在代码的顶层捕获异常,并做任何你喜欢的事情。 (在某些时候实际退出可能是礼貌的,当然.sys.exit(exitcode)会这样做 - 引发另一个SystemExit
异常。)



When the Python runtime system wants to exit, it raises a SystemExit
exception.

Catch that exception at the top level of your code, and do whatever
you like. (It might be polite to actually exit at some point, of
course. sys.exit(exitcode) will do so -- raising another SystemExit
exception.)




我认为使用atexit模块 -
更清洁


-

劳伦斯 -

"任何人都可以随心所欲地使用他想要的任何东西,但最后的光线是隧道的大部分问题是:



I think using atexit module -
http://docs.python.org/lib/module-atexit.html is cleaner

--
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"

这篇关于关机钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 14:36
查看更多