xonsh/xontrib/mpl.py

67 lines
1.7 KiB
Python
Raw Normal View History

2017-02-19 17:49:40 -05:00
"""Matplotlib xontribution. This xontrib should be loaded before matplotlib
is imported.
"""
2016-05-08 20:17:48 -04:00
2017-02-12 17:16:42 +08:00
from xonsh.tools import unthreadable
2017-02-19 15:40:06 -05:00
from xonsh.lazyasd import lazyobject
2016-05-08 20:17:48 -04:00
2016-08-04 19:19:28 -04:00
__all__ = ()
2016-07-18 11:30:57 +02:00
2016-08-04 22:28:21 -04:00
2017-02-12 17:16:42 +08:00
@unthreadable
2016-08-04 19:19:28 -04:00
def mpl(args, stdin=None):
2016-05-08 20:17:48 -04:00
"""Hooks to matplotlib"""
2016-05-08 22:57:01 -04:00
from xontrib.mplhooks import show
2019-04-26 11:11:11 -04:00
2016-05-08 20:17:48 -04:00
show()
2019-04-26 11:11:11 -04:00
aliases["mpl"] = mpl
2017-02-19 15:40:06 -05:00
@lazyobject
def pylab_helpers():
try:
import matplotlib._pylab_helpers as m
except ImportError:
m = None
return m
@events.on_import_post_exec_module
def interactive_pyplot(module=None, **kwargs):
"""This puts pyplot in interactive mode once it is imported."""
2019-04-26 11:11:11 -04:00
if module.__name__ != "matplotlib.pyplot" or not __xonsh__.env.get(
"XONSH_INTERACTIVE"
):
2017-02-19 15:40:06 -05:00
return
2017-02-19 17:49:40 -05:00
# Since we are in interactive mode, let's monkey-patch plt.show
# to try to never block.
2017-02-19 15:40:06 -05:00
module.ion()
module._INSTALL_FIG_OBSERVER = False
2017-02-19 17:49:40 -05:00
plt_show = module.show
def xonsh_show(*args, **kwargs):
"""This is a monkey patched version of matplotlib.pyplot.show()
for xonsh's interactive mode. First it tries non-blocking mode
(block=False). If for some reason this fails, it will run show
in normal blocking mode (block=True).
2017-02-19 17:49:40 -05:00
"""
kwargs.update(block=False)
rtn = plt_show(*args, **kwargs)
figmanager = pylab_helpers.Gcf.get_active()
if figmanager is not None:
# unblocked mode failed, try blocking.
kwargs.update(block=True)
rtn = plt_show(*args, **kwargs)
return rtn
module.show = xonsh_show
2017-02-19 15:40:06 -05:00
# register figure drawer
@events.on_postcommand
def redraw_mpl_figure(**kwargs):
"""Redraws the current matplotlib figure after each command."""
2017-02-19 17:49:40 -05:00
pylab_helpers.Gcf.draw_all()