如何在终止 Python 脚本时运行清理

发布于 2024-09-06 16:43:40 字数 337 浏览 13 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

叹沉浮 2024-09-13 16:43:40

尝试一下 atexit 标准模块怎么样?

它允许您注册一个将在终止时执行的函数。

How about trying the atexit standard module?

It allows you to register a function that will be executed upon termination.

踏月而来 2024-09-13 16:43:40

你正在使用 Unix 吗?如果是,为什么不在子进程中捕获 SIGTERM?事实上,Process.terminate() 的文档如下:(

Terminate the process. On Unix this is done using the SIGTERM signal

我还没有对此进行测试。)

Are you working with Unix? If yes, why not catch SIGTERM in the subprocesses? In fact, the documentation of Process.terminate() reads:

Terminate the process. On Unix this is done using the SIGTERM signal

(I have not tested this.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文