Constructing and solving any Gurobi model requires creating a Gurobi environment. While in other APIs Gurobi environments must be explicitly created and destroyed, gurobipy includes the default environment. The default environment simplifies matters when you are actively experimenting with model formulation in an interactive environment (e.g. the Gurobi interactive shell, an open python interactive interpreter like python itself or IPython, or a Jupyter notebook).
Many of our examples codes (e.g. mip1.py) use a pattern that uses the default environment and does not explicitly dispose of it at the end of the code. These examples are intended only to illustrate basic usage of key features of gurobipy. In production systems you should be more careful: we recommend explicitly managing environments to prevent resource leaks. This is particularly important when remote resources are involved or if there are usage limits on your license, i.e.
-
- Compute server
- A floating use/token server license
- A WLS license
- A single use license
- Instant cloud
The correct way to manage environments in Python is to use context managers, just as you should whenever opening a file or starting a connection in Python. Below are two possible patterns; the example mip1_remote.py provides a more complete code.
- To solve a single model tied to a single environment:
import gurobipy as gp
with gp.Env() as env, gp.Model(env=env) as model:
# construct, solve, and post-process `model`
x = model.addVar()
...
model.optimize()
...
# at the end of the block, the environment is explicitly freed,
# even if there is an error. This returns resources to the compute
# server or instant cloud, or releases limited use licenses so
# that tokens are not held for too long.
- To use multiple models in sequence within an environment:
import gurobipy as gp
with gp.Env() as env:
with gp.Model(env=env) as model1:
# formulate and solve model1
with gp.Model(env=env) as model2:
# formulate and solve model2