Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that pylab backend of matplotlib runs inline?

I am modifying a python module that plots some special graphs using matplotlib.

Right now, this module just saves all figures as files.

I would like to make it possible to import the module while working in ipython notebook and see the results "inline", on the other hand I would like to keep the default functionality of saving the figures as files when the module is imported in all other cases.

So I need somehow to check if the module is imported in ipython notebook and the pylab is operating inline or not.

How can I check this?

like image 247
Stanpol Avatar asked Mar 11 '13 14:03

Stanpol


2 Answers

You can check the matplotlib backend with:

import matplotlib
matplotlib.get_backend()

To check for inline matplotlib in particular:

mpl_is_inline = 'inline' in matplotlib.get_backend()

Note that with the IPython notebook, you can always display inline figures, regardless of the active matplotlib backend, with:

display(fig)
like image 150
minrk Avatar answered Oct 22 '22 22:10

minrk


What about trying:

try:
    cfg = get_ipython().config
    print('Called by IPython.')

    # Caution: cfg is an IPython.config.loader.Config
    if cfg['IPKernelApp']:
        print('Within IPython QtConsole.')

        try:
            if cfg['IPKernelApp']['pylab'] == 'inline':
                print('inline pylab loaded.')
            else:
                print('pylab loaded, but not in inline mode.')
        except:
            print('pylab not loaded.')
    elif cfg['TerminalIPythonApp']:
        try:
            if cfg['TerminalIPythonApp']['pylab'] == 'inline':
                print('inline pylab loaded.')
            else:
                print('pylab loaded, but not in inline mode.')
        except:
            print('pylab not loaded.')
except:
    print('Not called by IPython.')
like image 33
Ioannis Filippidis Avatar answered Oct 22 '22 21:10

Ioannis Filippidis