You can detect whether Matplotlib is running in interactive mode or whether your environment can show plots, and then either display or save the figure.
if is_interactive():
plt.show()
else:
plt.savefig("plot.png")
import matplotlib
import matplotlib.pyplot as plt
import sys
# Detect if running interactively
def is_interactive():
return hasattr(sys, 'ps1') or sys.flags.interactive or matplotlib.is_interactive()
# Example plot
plt.plot([1, 2, 3], [4, 9, 16])
plt.title("Example Plot")
# Show or save depending on mode
if is_interactive():
plt.show()
else:
plt.savefig("plot.png")
print("Plot saved to plot.png")
hasattr(sys, 'ps1') → True in an interactive terminal (e.g. Python REPL or IPython).sys.flags.interactive → True if Python was launched with -i.matplotlib.is_interactive() → True if matplotlib’s interactive mode is on (plt.ion()).plt.show() → Opens a window if possible.plt.savefig() → Writes to a file if no GUI is available or script is non-interactive.If you know your code will often run headless (like in servers or CI):
import matplotlib
import sys
if not hasattr(sys, 'ps1'):
matplotlib.use('Agg') # Non-interactive backend
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 9, 16])
plt.title("Server-safe Plot")
if hasattr(sys, 'ps1'):
plt.show()
else:
plt.savefig("plot.png")
This explicitly switches Matplotlib to a non-GUI backend (Agg) when not in interactive mode — ensuring it won’t crash on systems without a display.