How to check that pylab backend of matplotlib runs inline?

↘锁芯ラ 提交于 2019-11-30 05:10:44

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)

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.')

This got me searching, and I think I've found a solution. Not sure if this is actually documented or even intended, but it may very well work:

get_ipython().config['IPKernelApp']['pylab'] == 'inline'

get_ipython() appears to be a method only defined when running IPython; it returns what I assume is the current IPython session. Then, you can access the config attribute, which is a dictionary, that includes the 'IPKernelApp' element. The latter is a dictionary in itself that can contain a key pylab, which can be the string 'inline'.

I haven't tried extensively, but I'm guessing that the above line of code will evaluate to False if you're not running pylab inline.

More importantly, it will raise a KeyError when you're not running the notebook or the pylab option, so you'll need to catch that and take that raised exception as "no" for running a notebook with pylab inline.

Finally, get_ipython() may throw a NameError, and similar to the above, that of course also means you're not running IPython.

I've only tested this minimally, but importing this in my IPython notebook, and then on the default Python cmdline does show it to work.

Let us know if this works for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!