3

I'm writing python using jupyter notebook and I have two cells that can influence each other.

I'm wondering is it possible to leave some certain cells out after I click Restart & Run All so that I can test the two cells independently?

dyluns
  • 155
  • 9

4 Answers4

3

One option based on Davide Fiocco's answer of this post and that I just tested is to include %%script magic command on each cell you don't want to execute. For example

%%script false --no-raise-error
for i in range(100000000000000):
    print(i)
datapug
  • 2,261
  • 1
  • 17
  • 33
3

I recently discovered an easy way to do this.

You may have noticed that cells can be set as type Code or Markdown - this lets you prepare the notebook with headers and explanatory text (in Markdown), but also sections of executable code (the default). This can be set from a drop-down already on the screen if using via Jupyter Lab. In Jupyter Notebook I think it's under the Cells menu. You can also use keyboard shortcuts (first hit Escape if needed to get out of text-entry mode: Y for Code, Mfor Markdown, or Rfor Raw.

Wait, what's that about Raw? It appears to just take away the code highlighting and make the cell not executable! So Esc+R to make it Raw, then execute like you wanted to, then Esc+Y if you want to re-enable that block.

Alternative: If you want a quicker way to comment out all the lines but leave it as a Code block, make sure you are in edit mode (click on the cell contents), do Ctrl+A (for select-all), and then Ctrl+/ (for "comment this line"). I tested with python and it inserts # at the beginning of each selected line.

Starman
  • 336
  • 2
  • 11
2

One option is to create a parameter and run the cells accordingly

x = 1

# cell 1
if x == 1:
    // run this cell

# cell 2
if x != 1:
    // run the other cell

In this example, you will skip cell 2.

smttsp
  • 4,011
  • 3
  • 33
  • 62
1

If you put those two cells at the end of the page, you can run all cells above a certain cell with a single click.

That or you can put a triple-quote at the beginning and end of the two cells, then un-quote the cells to test them.

katardin
  • 596
  • 3
  • 14