以下是一种可行的方法,但并不适用于所有环境:import matplotlib.pyplot as plt
import sys
import matplotlib
def plt_show_interactive():
"""Show plot windows, with interaction if possible; prompt to continue."""
in_ipython = ('get_ipython' in globals())
inline_backend = ('inline' in matplotlib.get_backend())
in_linux = (sys.platform == 'linux')
if inline_backend:
plt.show()
elif not in_linux and in_ipython:
print("Press Ctrl-C to continue.")
try:
while True:
plt.pause(0.5)
except KeyboardInterrupt:
print("Continuing.")
elif in_linux and not in_ipython:
# Command line: plots are interactive during wait for input.
plt.show(block=False)
input("Press ENTER to continue.")
elif in_linux and in_ipython:
# Loop with plt.pause(1) causes repeated focus stealing.
plt.pause(1)
print("Sorry, plots are not interactive until program has finished.")
elif not in_linux and not in_ipython:
# Ctrl-C is handled differently here.
plt.pause(1)
input("Sorry, not interactive. Press ENTER to continue.")
def prompt_if_not_ipython(verb="end"):
"""Ask user to press ENTER if not we're not inside IPython."""
if ('get_ipython' not in globals()):
input("Press ENTER to %s." % verb)
fig, ax = plt.subplots(1, 1, tight_layout=True)
ax.plot([0,1,2],[0,3,2])
plt_show_interactive()
prompt_if_not_ipython()