Last active
April 11, 2022 10:24
-
-
Save djwbrown/3e24bf4e0c5e9ee156a5 to your computer and use it in GitHub Desktop.
matplotlib.pyplot blackmagic to make CTRL-C work again
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import matplotlib.pyplot as plt | |
try: | |
# Put matplotlib.pyplot in interactive mode so that the plots are shown in a background thread. | |
plt.ion() | |
while(True): | |
plt.show() | |
except KeyboardInterrupt: | |
print "" | |
sys.exit(0) |
More simple solution: Add at beginning of your program
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My use-case involved updating a figure in a for-loop and exit the app once the user requests the termination. In the below example, the user can exit the loop prematurely in three ways:
The nice thing is that figure/axes can be reused over multiple iterations.
The code below requires python3+. I tested with matplotlib 3.4.1 and python3.8.