Magic commands (5 minutes)
Note
In Jupyter, “magic” refers to additional commands added by Jupyter to the kernel environment that aren’t normally part of that kernel’s language.1 I’m going to start with a slightly exotic magic command because I think you’ll find it useful.
In a new cell in the Python notebook we just worked with, execute this command:2
%jsroot on
Note
As a general rule, magic commands begin with the percent sign “%”.3
Draw the canvas again:
my_canvas.Draw()
Move the cursor over the new plot.
Note
Ah, that’s more like it! The plot is not interactive in the same way as in X-Windows ROOT, but you can get a lot done. Play around a bit, looking at tooltips and right-clicking. Note the faint icons below the lower left-hand corner of the plot.
If you execute %lsmagic
you’ll see a list of available magic
commands. There’s probably more here than you can absorb right now.4
Here are examples of the magic commands I find to be the most useful:
%mkdir subdirectory
%cp ~seligman/root-class/jsroot-test.ipynb subdirectory
%ls subdirectory
%less c1.C
%man root
%cd subdirectory
The above commands are “line magics,” which are executed line-by-line within a cell. There are also “cell magics” that affect the contents of the entire cell in which they appear; they must appear as the first line in a cell. They begin with a double “%”. Examples:
%%writefile
(write the cell to file ); %%timeit
(execute the cell many times and determine the average execution time);%%sh
(execute the cell as a UNIX shell script).
- 1
No, nothing to do with Doctor Strange or Gandalf, though you may find yourself muttering “You shall not pass!” as you work with ROOT.
- 2
Note that the
%jsroot
magic command is only available in Python-based notebooks after you’ve executedimport ROOT
orfrom ROOT import...
In ROOT C++ notebooks it’s built-in.“JSROOT” is short for “Javascript ROOT”; it’s an evolving project to bring more interactivity of ROOT graphics into web browsers.
- 3
Well… not really. There’s an option
(%automagic on|off
) that allows you to omit the leading %. In this tutorial I’ll always include the % prefix to make it clear when a command is “magic”.- 4
Here are more details about magic commands.