Skip to content

Commit

Permalink
ENH: webagg: Handle ioloop shutdown correctly
Browse files Browse the repository at this point in the history
This change correctly cleans up after the ioloop is
interrupted, allowing the user to call plt.show(),
then resume control with a SIGINT, then call plt.show() again.
  • Loading branch information
perimosocordiae committed Apr 30, 2016
1 parent 35e2781 commit 500e6fd
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions lib/matplotlib/backends/backend_webagg.py
Expand Up @@ -15,14 +15,15 @@

from matplotlib.externals import six

import datetime
import errno
import json
import os
import random
import sys
import signal
import socket
import threading
from contextlib import contextmanager

try:
import tornado
Expand Down Expand Up @@ -323,26 +324,39 @@ def start(cls):
if cls.started:
return

# Set the flag to True *before* blocking on IOLoop.instance().start()
cls.started = True

"""
IOLoop.running() was removed as of Tornado 2.4; see for example
https://groups.google.com/forum/#!topic/python-tornado/QLMzkpQBGOY
Thus there is no correct way to check if the loop has already been
launched. We may end up with two concurrently running loops in that
unlucky case with all the expected consequences.
"""
print("Press Ctrl+C to stop WebAgg server")
sys.stdout.flush()
try:
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
ioloop = tornado.ioloop.IOLoop.instance()

def shutdown():
ioloop.stop()
print("Server is stopped")
sys.stdout.flush()
finally:
cls.started = False

@contextmanager
def catch_sigint():
old_handler = signal.signal(
signal.SIGINT,
lambda sig, frame: ioloop.add_callback_from_signal(shutdown))
try:
yield
finally:
signal.signal(signal.SIGINT, old_handler)

# Set the flag to True *before* blocking on ioloop.start()
cls.started = True

print("Press Ctrl+C to stop WebAgg server")
sys.stdout.flush()
with catch_sigint():
ioloop.start()


def ipython_inline_display(figure):
import tornado.template
Expand Down

0 comments on commit 500e6fd

Please sign in to comment.