Python script switching between matplotlib inline and QT backend
Question: I would like to be able to switch between displaying matplotlib graphs inline
or using QT backend in a script file based on a variable called inlinemode
such as the code fragment below

    
    
    import matplotlib.pylab as plt
    inlinemode = False
    if inlinemode:   
        print "plot will be inline..."
    else:
        print "plot will be qt..."
        plt.switch_backend('qt4agg')
    plt.figure()
    plt.plot(range(10))
    

My IPython console starts in inline mode by default, and executing the code
fragment above still produces an inline graph instead of a qt window. If it
was possible to send the IPython magic %matplotlib inline -or- %matplotlib qt
in the if block, this would accomplish this task. However, from what I have
been able to gather, it is not possible to send these magic's from a script
file.

Any suggestions would be greatly appreciated!

(FYI: I am running from Spyder in Anaconda Python 2.7 on Windows 10)


Answer: This is possible using the following block, which will allow the script to be
run in IPython using `%run` or directly through standard python.

    
    
    try:
        import IPython
        shell = IPython.get_ipython()
        shell.enable_matplotlib(gui='inline')
    except:
        pass   
    

This is what the magic `%matplotlib inline` is actually doing under the hood.
You can change the keyword argument to be `gui='qt'` to select a different
backend.

