diff --git a/book/vscode-ext/src/providers/qmdPythonValueResolver.ts b/book/vscode-ext/src/providers/qmdPythonValueResolver.ts index fd781ade0..f4872b500 100644 --- a/book/vscode-ext/src/providers/qmdPythonValueResolver.ts +++ b/book/vscode-ext/src/providers/qmdPythonValueResolver.ts @@ -111,12 +111,19 @@ function buildResolverScript(pythonSource: string, varNames: string[]): string { // We also suppress plt.show() so it's a no-op. const lines = [ 'import sys, json, os', + '# Force non-interactive backend BEFORE any matplotlib import.', + '# Setting the env var ensures even lazy imports pick up Agg.', 'os.environ["MPLBACKEND"] = "Agg"', + 'os.environ["MATPLOTLIB_BACKEND"] = "Agg"', 'try:', ' import matplotlib', - ' matplotlib.use("Agg")', + ' matplotlib.use("Agg", force=True)', ' import matplotlib.pyplot as _plt', + ' _plt.switch_backend("Agg")', ' _plt.show = lambda *a, **k: None', + ' _plt.pause = lambda *a, **k: None', + ' # Close any figures that might have been created during import', + ' _plt.close("all")', 'except ImportError:', ' pass', '', @@ -133,6 +140,13 @@ function buildResolverScript(pythonSource: string, varNames: string[]): string { '# Execute the QMD Python blocks', pythonSource, '', + '# Close any figures created during execution', + 'try:', + ' import matplotlib.pyplot as _plt2', + ' _plt2.close("all")', + 'except Exception:', + ' pass', + '', '# Collect variable values', '_results = {}', captures,