2

I have been using some jupyter notebook magics such as %matplotlib inline.

How to load them using python script instead of % signs.

Using jupyter

%load_ext sql
%config SqlMagic.displaycon=False

Question: How to do the same using script?

# file: myimports.py
from something import x
x.load_ext('sql')
x.config('SqlMagic.displaycon',False)

I want to use import * from myimports.py in jupyter notebook, so that I don't have to type %load_ext sql and so many things everytime I create new jupyter notebooks.

5
  • Maybe this notebook helps your for matplotlib. Not sure if there exists a rule for this. Commented Apr 7, 2022 at 19:49
  • 1
    With regards to your %matplotlib example, what is your goal? %matplotlib is to set how the plotting output is handled in the notebook. If it is going to be a script run not connected to a display interface, then you don't want an equivalent for that. You may want to have it save a figure of your plot that you can view later, e.g., plt.savefig("my_plot.png"). If you are going to return a plot that the notebook than can handle as previously set like the bottom of what @mosc9575 referenced, then you still don't include an equivalent because it would already be handled in the notebook. Commented Apr 7, 2022 at 20:31
  • This example here shows SQL code with and without magics enabled. It would be similar to that in your script. Commented Apr 7, 2022 at 20:34
  • I want python script, so that i can import these settings from myimport.py into the notebook. from myimports import * Commented Apr 7, 2022 at 20:42
  • 2
    Maybe this can help? You can create a sort of setup notebook with all needed magics and import it using %run Commented Apr 13, 2022 at 9:45

1 Answer 1

4
+25

You can run IPython line magic using IPython interactiveshell:

from IPython.terminal.interactiveshell import TerminalInteractiveShell
shell:TerminalInteractiveShell = TerminalInteractiveShell.instance()
shell.run_line_magic("load_ext","sql")
shell.run_line_magic("config","SqlMagic.displaycon=False") 
# or shell.config["SqlMagic"]={'displaycon': False}

run_line_magic(magic_name, line_after_magic)

you can even run cd

shell.run_line_magic("cd","..")

And it will work.

However, there is some magic that not working with TerminalInteractiveShell because it can't access your code (alias, page, ...).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.