I use cp_sat
from ortools.sat.python
to solve a constraint programming problem. However, my Python interpreter just stops in the middle of a solve, without printing a stacktrace.
from ortools.sat.python import cp_model
model = cp_model.CpModel()
solver = cp_model.CpSolver()
print('Solver started')
status = solver.Solve(model, SolutionLogger())
print('Solver finished') # This line is never reached
What can be the problem?
It turns out that the on_solution_callback
of cp_sat
can’t handle exceptions. This will produce Fatal Python error, which can be made explicit using the faulthandler
library:
from ortools.sat.python import cp_model
import faulthandler
faulthandler.enable()
class SolutionLogger(cp_model.CpSolverSolutionCallback):
def on_solution_callback(self):
raise Exception('Solution found')
Solve this by catching the excption in the on_solution_callback
.