支持多处理的ATEXIT替换
multiexit的Python项目详细描述
更好、更理智、更有用的atexit替代python 3,它支持 multiprocessing。
灵感来自下面的stackoverflow问题和建筑经验 多处理守护进程:
https://stackoverflow.com/q/2546276
multiexit将安装sigterm信号的处理程序并执行 已注册的退出函数,在$ $ }。
可以注册退出函数,以便只有调用进程将调用 它们(默认值),或作为^ {EM1}$ $共享的EME>退出函数,将由 调用进程和继承它的所有子进程。API
在主进程上,在分叉或创建任何子进程之前, 呼叫multiexit.install:
install(signals=(signal.SIGTERM,),except_hook=True)
signals: | Signals to install handler. Usually only ^{tt4}$ is required. |
---|---|
except_hook: | Also install a sys.excepthook that will call the exit functions in case of an unexpected exception. |
然后,对于每个退出函数,在任何子进程上,调用^ {tT5} $:
register(func,shared=False)
func: | Exit function to register. Any callable without arguments. |
---|---|
shared: | If ^{tt6}$, the exit function will be called by the calling process but also by all the children subprocesses that inherit it (thus the ones created after registering it). If ^{tt6}$ is ^{tt8}$, the default, only the calling process will execute the exit function. |
示例
fromtimeimportsleepfromsignalimportSIGTERMfromosimportkill,getpidfrommultiprocessingimportProcessfrommultiexitimportinstall,register,unregisterif__name__=='__main__':# Always call install() on the main process before creating any# subprocess## This will install a required handler for SIGTERM. Subprocesses must# inherit this handler. Plus it assigns a pid as the master process# for exit or os._exit call.install()def_subproc1():@registerdefsubproc1_clean():print('Subprocess clean!')sleep(1000)# Register shared exit function so all subprocess call thisdefshared_exit():print('Shared exit being called by {} ...'.format(getpid()))register(shared_exit,shared=True)subproc1=Process(name='SubProcess1',target=_subproc1,)# proc.daemon = True# daemon means that signals (like SIGTERM) will be propagated automatically# to children. Set to false (the default), to handle the SIGTERM# (process.terminate()) to the children yourself.subproc1.start()# Register a cleaner using a decorator@registerdefclean_main():print('Terminating child {}'.format(subproc1.pid,))subproc1.terminate()subproc1.join()print('Child {} ended with {}'.format(subproc1.pid,subproc1.exitcode,))# Wait, and then kill main processsleep(3)# Suicidekill(getpid(),SIGTERM)
有关更广泛的示例,请查看example.py。
许可证
Copyright (C) 2018 KuraLabs S.R.L Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.