Skip to content

Commit db52dde

Browse files
committed
Improve error message if the runtime fails to load
1 parent 3f12469 commit db52dde

File tree

1 file changed

+28
-11
lines changed

1 file changed

+28
-11
lines changed

pythonnet/__init__.py

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ def set_runtime(runtime: Union[clr_loader.Runtime, str], **params: str) -> None:
2828

2929

3030
def get_runtime_info() -> Optional[clr_loader.RuntimeInfo]:
31+
"""Retrieve information on the configured runtime"""
32+
3133
if _RUNTIME is None:
3234
return None
3335
else:
@@ -52,22 +54,39 @@ def _get_params_from_env(prefix: str) -> Dict[str, str]:
5254
def _create_runtime_from_spec(
5355
spec: str, params: Optional[Dict[str, Any]] = None
5456
) -> clr_loader.Runtime:
57+
was_default = False
5558
if spec == "default":
59+
was_default = True
5660
if sys.platform == "win32":
5761
spec = "netfx"
5862
else:
5963
spec = "mono"
6064

6165
params = params or _get_params_from_env(spec)
6266

63-
if spec == "netfx":
64-
return clr_loader.get_netfx(**params)
65-
elif spec == "mono":
66-
return clr_loader.get_mono(**params)
67-
elif spec == "coreclr":
68-
return clr_loader.get_coreclr(**params)
69-
else:
70-
raise RuntimeError(f"Invalid runtime name: '{spec}'")
67+
try:
68+
if spec == "netfx":
69+
return clr_loader.get_netfx(**params)
70+
elif spec == "mono":
71+
return clr_loader.get_mono(**params)
72+
elif spec == "coreclr":
73+
return clr_loader.get_coreclr(**params)
74+
else:
75+
raise RuntimeError(f"Invalid runtime name: '{spec}'")
76+
except Exception as exc:
77+
if was_default:
78+
raise RuntimeError(
79+
f"""Failed to create a default .NET runtime, which would
80+
have been "{spec}" on this system. Either install a
81+
compatible runtime or configure it explicitly via
82+
`set_runtime` or the `PYTHONNET_*` environment variables
83+
(see set_runtime_from_env)."""
84+
) from exc
85+
else:
86+
raise RuntimeError(
87+
f"""Failed to create a .NET runtime ({spec}) using the
88+
parameters {params}."""
89+
) from exc
7190

7291

7392
def set_runtime_from_env() -> None:
@@ -92,9 +111,7 @@ def set_runtime_from_env() -> None:
92111
set_runtime(runtime)
93112

94113

95-
def load(
96-
runtime: Union[clr_loader.Runtime, str, None] = None, **params: str
97-
) -> None:
114+
def load(runtime: Union[clr_loader.Runtime, str, None] = None, **params: str) -> None:
98115
"""Load Python.NET in the specified runtime
99116
100117
The same parameters as for `set_runtime` can be used. By default,

0 commit comments

Comments
 (0)