How to run a single line or selected code in a Jupyter Notebook or JupyterLab cell?

28,839

Updated answer

As there have been a few updates of JupyterLab since my first answer (I'm now on 1.1.4), and it has been stated that JupyterLab 1.0 will eventually replace the classic Jupyter Notebook, here's what I think is the best approach right now and even more so in the time to come:

In JupyterLab use Run > Run selected line or highlighted text with an assigned keyboard shortcut to run code in the console.

Here's how it will look like when you run the three print statements line by line using a keyboard shortcut:

enter image description here

Here's how you set up a shortcut in Settings > Advanced Settings > Keyboard shortcuts:

enter image description here

And here's what you need to add under Settings > Keyboard Shortcuts > User preferences > :

{
    // List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:run-in-console",
            "keys": [
                "F9"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}

The shortcut will even show in the menu. I've chosen to use F9

enter image description here


Original answer for older versions:


Short answer:

Jupyter notebook:

  1. qtconsole
  2. scratchpad

JupyterLab:

  1. qtconsole
  2. Run > Run Selected Text or Current Line in Console, optionally with a keyboard shortcut

Have a look at the details below, as well as some special cases in an edit at the very end of the answer.


The details:

Jupyter Notebook option 1: qtconsole

The arguably most flexible alternative to inserting new cell is to open an IPython console using the magic function

%qtconsole

For a bit more fancy console you can use

%qtconsole --style vim

The results of the lines executed in this console will also be available to the Jupyter Notebook since it's still the same kernel that's running. One drawback is that you'll have to copy&paste or type the desired lines into the console.

[qtconsole1

Jupyter Notebook option 2: Scratchpad Notebook Extension

With a successful installation you can launch a Scratchpad with ctrl + B:

enter image description here

JupyterLab option 1: %qtconsole

Works the same way as for a Notebook

JupyterLab option 2: Run > Run Selected Text or Current Line in Console

A similar option to a qtconsole, but arguably more elegant, has been built in for newer versions of JupyterLab. Now you canput your marker on a single line, or highlight a selection, and use the menu option Run > Run Selected Text or Current Line in Console:

enter image description here

You're still going to get your results in an IPython console, but you don't have to add an extra line with %qtconsole and it's much easier to run a selection of lines within a cell:

enter image description here

You can make things even easier by assigning a keyboard shortcut to the menu option Run > Run Selected Text or Current Line in Console like this:

1 - Go to Settings and select Advanced Settings editor:

2 - Under the Keyboard shortcuts tab, do a ctrl+F search for run-in-console to locate the following section:

// [missing schema title]
    // [missing schema description]
    "notebook:run-in-console": {
      "command": "notebook:run-in-console",
      "keys": [
        ""
      ],
      "selector": ".jp-Notebook.jp-mod-editMode",
      "title": "Run In Console",
      "category": "Notebook Cell Operations"
    }

3 - Copy that part and paste it under User Overrides and type in your desired shortcut below keys like so:

[...]
"keys": [
  "F9"
],
[...]

4 - Click Save All under File.

5 - If the process went smoothly, you'll see that your menu option has changed:

enter image description here

6 - You may have to restart JupyterLab, but now you can easily run a single line or selection of lines with your desired shortcut.

##EDIT: Special cases

Your preferred approach will depend on the nature of the output of the lines in question. Below is an example with plotly. More examples will possibly be added with time.

1. - plotly

plotly figures will not be displayed directly in a Jupyter QtConsole (possibly related to this), but both the Scratchpad in a Jupyter Notebook and the integrated console in Jupyterlab using Run > Run Selected Text or Current Line in Console will handle plotly figures just fine.

Snippet:

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
init_notebook_mode(connected=True)

trace0 = go.Scatter(
    x=[1, 2, 3, 4],
    y=[10, 15, 13, 17]
)

fig = go.Figure([trace0])
iplot(fig)

1.1 - plotly with scratchpad

enter image description here

1.2 - plotly with JupyterLab console using highlighted line and keyboard shortcut:

enter image description here

Share:
28,839
vestland
Author by

vestland

No mystery. Lots of air. And some resources: Small snippets of great use: # pandas dataframes in and out os.listdir(os.getcwd()) os.getcwd() os.chdir('C:/repos/py_research/import') df = pd.read_clipboard(sep='\\s+') df = df.astype(str) df = df.apply(lambda x: x.str.replace(',','.')) df = df.astype(float) df = pd.read_csv(r'C:\dbs.csv',sep = ",", header = None) df.to_csv(r'C:\dbs.csv', sep=',', float_format='%.2f', decimal = '.', index=False) # replaze zeros df = df.replace({'0':np.nan, 0:np.nan}) IPython magic %prun #Show how much time your program spent in each function !ls *.csv # execute shell command inside notebook A few SO posts I always come back to: SO link magic How to make good reproducible pandas examples Python Pandas Counting the Occurrences of a Specific value How to get all images posted by me? Some valuable resources: Plotly: Python figure reference Plotly: x-axis tickformat, dates Plotly: Scatter plots with python Plotly: Gantt charts with python IPython: 28 tips Google Chrome inspect elements Installations: conda config --set ssl_verify False # https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html Anaconda installer archive Datasets: plotly Windows Commands https://www.howtogeek.com/194041/how-to-open-the-command-prompt-as-administrator-in-windows-8.1/ IDEs #VSCode https://code.visualstudio.com/docs/python/environments How to map arguments in functions: def SetColor(x): if(x == 'A'): return "1" elif(x == 'B'): return "2" elif(x == 'C'): return "3" lst = ['A', 'B', 'C'] list(map(SetColor, lst))

Updated on October 06, 2020

Comments

  • vestland
    vestland over 3 years

    In both JupyterLab and Jupyter Notebook you can execute a cell using ctrl + Enter:

    Code:

    print('line 1')
    print('line 2')
    print('line 3')
    

    Cell and output:

    cell and output

    But how can you run only line 2? Or even a selection of lines within a cell without running the entire cell? Sure you could just insert a cell with that single line or selection of lines, but that gets really cumbersome and messy really quick. So are there better ways of doing this?

  • eric
    eric over 2 years
    Yikes why isn't this just built into Jupyter? Seems you have researched it you can be the PR hero we all need :)
  • vestland
    vestland over 2 years
    @Eric Haha! Happy to be of service!
  • Frederich
    Frederich over 2 years
    Hi! I've been using this function but now I've a problem with that. I'm using conda with an enviroment that is running R 3.6.3 but the console by default execute R 3.6.0 (using the configuration you have explained). How can I set wich version to use?
  • getup8
    getup8 about 2 years
    Is there not a way to run selected text and output in the notebook itself instead of the console?
  • Moritz
    Moritz almost 2 years
    Agree with @getup8, for me it just opens the console and that's not the solution I'm looking for. Can the selected code not just be outputted directly underneath the cell in the notebook?