fix: plot_wave plt.show() crash when called non-interactively

Add show=False parameter to plot_wave(); when called from dynamics.py,
pass show=False and set matplotlib Agg backend to avoid NonGuiException.
Also print full traceback on failure for easier debugging.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-13 08:10:16 +08:00
parent d371b28acc
commit 1cefe184d7
2 changed files with 13 additions and 4 deletions
+7 -1
View File
@@ -381,14 +381,20 @@ def run_case(config_path, runtime_base, input_dir="input", output_dir="output",
# 6. 波形能量动画(可选) # 6. 波形能量动画(可选)
if config.get("step_plot_wave", 0): if config.get("step_plot_wave", 0):
try: try:
import matplotlib
matplotlib.use("Agg") # 非交互式后端,避免弹窗/报错
import plot_wave as pw import plot_wave as pw
print("[run] 正在绘制波形与能量图…") print("[run] 正在绘制波形与能量图…")
pw.plot_wave( gif = pw.plot_wave(
str(output_dir_abs), str(output_dir_abs),
save_gif=int(config.get("plot_wave_save_gif", 0)), save_gif=int(config.get("plot_wave_save_gif", 0)),
save_mp4=int(config.get("plot_wave_save_mp4", 0)), save_mp4=int(config.get("plot_wave_save_mp4", 0)),
show=False,
) )
if gif:
print(f"[run] 波形 GIF 已保存: {gif}")
except Exception as e: except Exception as e:
import traceback; traceback.print_exc()
print(f"[run] 绘制波形图失败: {e}") print(f"[run] 绘制波形图失败: {e}")
+5 -2
View File
@@ -167,7 +167,7 @@ def compute_energy(x, y, z, vx, vy, vz, masses, mass_arr,
return ek_sys, us_sys, ug_sys, ugr_sys return ek_sys, us_sys, ug_sys, ugr_sys
def plot_wave(output_dir, save_gif=False, save_mp4=False): def plot_wave(output_dir, save_gif=False, save_mp4=False, show=True):
"""主绘图函数:读取 display.txt 并生成波形+能量动画。 """主绘图函数:读取 display.txt 并生成波形+能量动画。
Args: Args:
@@ -360,8 +360,11 @@ def plot_wave(output_dir, save_gif=False, save_mp4=False):
except Exception as e: except Exception as e:
print(f"[plot_wave] 警告: MP4 输出失败 ({e}),跳过") print(f"[plot_wave] 警告: MP4 输出失败 ({e}),跳过")
# ── 最后显示动画窗口 ── # ── 最后显示动画窗口(仅直接运行时)──
if show:
plt.show() plt.show()
else:
plt.close(fig)
return gif_path return gif_path