如何在终止 Python 脚本时运行清理
我有一个 python 脚本可以完成一些工作。我使用 multiprocessing.Pool 让一些工作人员为我执行一些命令。
我的问题是当我尝试终止脚本时。当我按下 Ctrl-C 时,我希望每个工作人员立即清理其实验(这是一些自定义代码,或者实际上甚至是子进程命令,而不仅仅是释放锁或内存)并停止。
我知道我可以使用信号处理程序捕获 Ctrl-C 。如何使 multiprocessing.Pool 的所有当前正在运行的工作进程终止,同时仍在执行清理命令?
Pool.terminate()
将没有用,因为进程将在没有清理的情况下终止。
I have a python script that does some jobs. I use multiprocessing.Pool
to have a few workers do some commands for me.
My problem is when I try to terminate the script. When I press Ctrl-C, I would like, that every worker immediately cleans up its experiment (which is some custom code, or actually even a subprocess command, not just releasing locks or memory) and stops.
I know that I can catch Ctrl-C with the signal handler. How can I make all current running workers of a multiprocessing.Pool
to terminate, still doing their cleanup command?
Pool.terminate()
will not be useful, because the processes will be terminated without cleaning up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下 atexit 标准模块怎么样?
它允许您注册一个将在终止时执行的函数。
How about trying the atexit standard module?
It allows you to register a function that will be executed upon termination.
你正在使用 Unix 吗?如果是,为什么不在子进程中捕获 SIGTERM?事实上,
Process.terminate()
的文档如下:(我还没有对此进行测试。)
Are you working with Unix? If yes, why not catch SIGTERM in the subprocesses? In fact, the documentation of
Process.terminate()
reads:(I have not tested this.)