防止/捕获SWIG包装的模块退出Python会话?
在导入的模块(用swig包装的C++)中使用一个似乎要调用的函数时,它有时会失败 问题是没有引发Python异常—在出现错误消息字符串后,它将退出到终端,并且函数调用之后的代码没有机会运行。i、 e.类似于:防止/捕获SWIG包装的模块退出Python会话?,python,python-3.x,swig,triangulation,Python,Python 3.x,Swig,Triangulation,在导入的模块(用swig包装的C++)中使用一个似乎要调用的函数时,它有时会失败 问题是没有引发Python异常—在出现错误消息字符串后,它将退出到终端,并且函数调用之后的代码没有机会运行。i、 e.类似于: import useful_module # Do stuff here useful_module.funtion_that_includes_call_to_triangle() # This crashes under certain conditions ### cleanup
import useful_module
# Do stuff here
useful_module.funtion_that_includes_call_to_triangle() # This crashes under certain conditions
### cleanup code here not run... outputs error below ###
# Internal error in segmentintersection():
# Topological inconsistency after splitting a segment.
# Please report this bug to jrs@cs.berkeley.edu
# Include the message above, your input data set, and the exact
# command line you used to run Triangle.
import multiprocessing as mp
import queue
import useful_module
# A serialisable worker function
def worker(q, other_args):
try:
# Do stuff here with usual try/except/raise
results = useful_module.funtion_that_includes_call_to_triangle()
q.put(results)
except Exception as e:
q.put(e)
q = mp.Queue()
p = mp.Process(target=worker, args=(q, other_args))
p.start()
p.join()
# Get results from worker
try:
results = q.get(block=False)
except queue.Empty:
print('No result. Triangle probably failed!')
# Do failure handling here
else:
# Check if an exception was raised by worker code
if isinstance(results, Exception):
raise results
# Continue as normal
我试图用一个try/except
来包围这条有问题的行,但由于它退出时没有引发错误,所以没有被捕获
如果在ipython
会话中尝试上述操作,它也将退出回到终端
有没有一种方法可以阻止它退出python会话,以便代码继续?目前,我的解决方案是将调用封装在辅助函数中,并使用
多处理.process作为新进程启动辅助函数。在我的案例中,可以使用队列传递和返回数据。传递由代码引起的异常是一件棘手的事情——我最后用try/except
和put
将结果包装到返回队列中。如果有更好的方法,请留下评论或回答
我已经包括了一些实现,以防有用
比如:
import useful_module
# Do stuff here
useful_module.funtion_that_includes_call_to_triangle() # This crashes under certain conditions
### cleanup code here not run... outputs error below ###
# Internal error in segmentintersection():
# Topological inconsistency after splitting a segment.
# Please report this bug to jrs@cs.berkeley.edu
# Include the message above, your input data set, and the exact
# command line you used to run Triangle.
import multiprocessing as mp
import queue
import useful_module
# A serialisable worker function
def worker(q, other_args):
try:
# Do stuff here with usual try/except/raise
results = useful_module.funtion_that_includes_call_to_triangle()
q.put(results)
except Exception as e:
q.put(e)
q = mp.Queue()
p = mp.Process(target=worker, args=(q, other_args))
p.start()
p.join()
# Get results from worker
try:
results = q.get(block=False)
except queue.Empty:
print('No result. Triangle probably failed!')
# Do failure handling here
else:
# Check if an exception was raised by worker code
if isinstance(results, Exception):
raise results
# Continue as normal
在触发崩溃的情况下,它只会杀死新创建的工作进程,并且父python进程仍然存在