首页 > 解决方案 > Python在新线程/进程中新导入外部模块(f2py)?

问题描述

我使用从带有 f2py 的 fortran 模块创建的外部模块,其中包含我重复运行的函数。

底层的fortran(我无法控制)有点挑剔,有时会在跟踪哪些数组已经分配时出现问题。发生这种情况时,下次我调用该函数时,会出现一个分段错误,导致整个 python 会话崩溃。

但是,我可以诊断何时出现此问题,即我知道下次调用该函数时是否会崩溃。我想知道此时是否有办法“全新”导入 f2py 模块。

我希望也许有一种方法可以将外部模块加载到单独的线程或进程中,以后可以将其杀死并重新开始?

我在想象这样的事情:

def funcwrapper():
    newprocess = start_new_process() #start a new process somehow
    newprocess.run('import f2py_module') #import f2py module into the new process
    newprocess.run('result = f2py_module.func()') #run the function
    result = newprocess.retrieve('result') #somehow get the result back into the main process
    newprocess.terminate() #kill the new process
    return result

我觉得这应该可以通过 MultiProcessing 或 Threading 实现,但我对这些没有太多经验。

标签: pythonsubprocesspython-importpython-multiprocessingf2py

解决方案


推荐阅读