mpiexec+python+^C:\u del\u方法未执行(且无回溯)

2024-04-29 11:02:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下test_mpi.pypython脚本:

from mpi4py import MPI
import time

class Foo:
    def __init__(self):
        print('Creation object.')
    def __del__(self):
        print('Object destruction.')

foo = Foo()
time.sleep(10)

如果我在不使用mpiexec的情况下执行它,使用一个简单的python test_mpi.py,在5s后按CTRL+C,我会得到以下输出:

ngreiner@Nathans-MacBook-Pro:~/Documents/scratch$ python test_mpi.py 
Creation object.
^CTraceback (most recent call last):
  File "test_mpi.py", line 26, in <module>
    time.sleep(10)
KeyboardInterrupt
Object destruction.
ngreiner@Nathans-MacBook-Pro:~/Documents/scratch$

如果我将它嵌入到mpiexec执行中,使用mpiexec -np 1 python test_mpi.py,在5s后再次按CTRL+C,我现在得到:

ngreiner@Nathans-MacBook-Pro:~/Documents/scratch$ mpiexec -np 1 python test_mpi.py 
Creation object.
^Cngreiner@Nathans-MacBook-Pro:~/Documents/scratch$

python的回溯和del方法的执行都消失了。 对我来说,主要的问题是没有执行\uu del \uuu方法,这应该会在我的实际应用中进行一些清理

当Python执行从mpiexec启动时,我怎么能执行uu del_uuuuuuu方法

非常感谢你的帮助

(我的系统配置:macOS High sierra 10.13.6、Python 3.7.4、open mpi 4.0.1、mpi4py 3.0.2。)


Tags: 方法pytestobjecttimedocumentspromacbook
2条回答

根据documentation,不能保证调用del。所以你很幸运,它被称为非mpi程序

对于简单的情况,可以使用try/finally来确保finally部分被执行。 或者更一般地说,使用context manager

以下是对文档的引用,在这里很重要:

It is not guaranteed that del() methods are called for objects that still exist when the interpreter exits.

经过一番搜索,我找到了一个解决方案,可以在mpiexec期间点击^C时恢复回溯的打印和uu del方法的执行

在正常的python执行过程中(不是由mpiexec启动的,直接从终端启动),点击^C会向python发送一个SIGINT信号,python会将其转换为KeyboardInterrupt异常(https://docs.python.org/3.7/library/signal.html

但是当在mpiexec执行期间点击^ C时,是mpiexec进程接收SIGINT信号,而不是将其传播到其子进程(例如python),而是向其子进程发送SIGTERM信号(https://www.open-mpi.org/doc/current/man1/mpirun.1.php

因此,python对SIGINT和SIGTERM信号的反应似乎并不相似

我找到的解决方法是使用signal模块,并对SIGTERM信号使用特定的处理程序,这只会引发一个KeyboardInterrupt。这可以通过以下方式实现:

def sigterm_handler():
    raise KeyboardInterrupt

import signal
signal.signal(signal.SIGTERM, sigterm_handler)

前者可以包含在执行的python脚本的顶部,或者,为了在每次python与mpiexec和mpi4py包一起使用时都保留此行为,可以包含在mpi4py包的uu init_u2;.py文件的顶部

这种策略可能会有副作用(我不知道),使用风险自负

相关问题 更多 >