28 Jupyter Notebook tips, tricks, and shortcuts

https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/


Edit IPython cell in an external editor

https://stackoverflow.com/questions/28309430/edit-ipython-cell-in-an-external-editor

This is what I came up with. I added 2 shortcuts:

  • 'g' to launch gvim with the content of the current cell (you can replace gvim with whatever text editor you like).
  • 'u' to update the content of the current cell with what was saved by gvim. So, when you want to edit the cell with your preferred editor, hit 'g', make the changes you want to the cell, save the file in your editor (and quit), then hit 'u'.

Just execute this cell to enable these features or put it in ~/.jupiter/custom/custom.js


In [1]:
%%javascript

IPython.keyboard_manager.command_shortcuts.add_shortcut('g', {
    help : 'Edit cell in Visual Studio Code',
    handler : function (event) {
        
        var input = IPython.notebook.get_selected_cell().get_text();
        
        var cmd = "f = open('.toto.py', 'w');f.close()";
        if (input != "") {
            cmd = '%%writefile .toto.py\n' + input;
        }
        IPython.notebook.kernel.execute(cmd);
        //cmd = "import os;os.system('open -a /Applications/MacVim.app .toto.py')";
        //cmd = "!open -a /Applications/MacVim.app .toto.py";
        cmd = "!code .toto.py";

        IPython.notebook.kernel.execute(cmd);
        return false;
    }}
);

IPython.keyboard_manager.command_shortcuts.add_shortcut('u', {
    help : 'Update cell from externally edited file',
    handler : function (event) {
        function handle_output(msg) {
            var ret = msg.content.text;
            IPython.notebook.get_selected_cell().set_text(ret);
        }
        var callback = {'output': handle_output};
        var cmd = "f = open('.toto.py', 'r');print(f.read())";
        IPython.notebook.kernel.execute(cmd, {iopub: callback}, {silent: false});
        return false;
    }}
);



In [2]:
n = int (input("Enter a number:"))
print("this is the number:{:10.3f}".format(n))


Enter a number:90
this is the number:    90.000

Debugging

(python)
from IPython.core.debugger import set_trace
...
set_trace()
..

or

import pdb; pdb.set_trace()

In [ ]:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"