简体   繁体   中英

Jupyter notebook: how to leave one cell out while 'run all'

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?

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)

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.

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 .

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, M for Markdown, or R for 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM