12

Is there a section divider in Spyder that is similar to R's '--'? Using '--' in R script automatically divide codes in different sections. One can find different sections, especially if the code is long. I wonder if there is a similar feature in Spyder.

Currently, I'm just using """ or ## such as

"""
Created on Mon Feb 11 11:24:15 2019

"""

or

##Section 1

They do not divide code in sections.

Ollie
  • 1,641
  • 1
  • 13
  • 31
Roger
  • 355
  • 1
  • 2
  • 15
  • maybe this is what you are looking for [link](https://stackoverflow.com/questions/54925458/what-is-outline-explorer-in-spyder/54925573#54925573) – sahasrara62 May 11 '19 at 03:02
  • 1
    Thank you. I also used #%%, but I have to execute all code in the block defined by #%%. I guess I need the divider to just divide the section instead of forcing me to run the code in the block every time I push the run button. – Roger May 11 '19 at 03:29
  • You can divide code as functions and call them. – kur ag May 11 '19 at 05:37

2 Answers2

15

I'm not sure how it works on R, but you can use lines that start with comments of the form:

# %%

Different parts of your code are separated by them and then you can run each section separately if you want.

Carlos Cordoba
  • 33,273
  • 10
  • 95
  • 124
s.devia10
  • 151
  • 1
  • 5
  • 1
    Using # %% as section heading is making all the code lines below it a single cell and when I'm running a single line, it only gives the output from the final line. Is there another way to make it work? – rahul-ahuja Nov 21 '20 at 00:57
13

Here are some examples :

Example 1 : One cell with navigable sections

#%% Notes

#### Defining Code Cells
# A “code cell” in Spyder is a block of lines, typically in a script, that can be 
# easily executed all at once.
# You can separate cells by lines starting with either: 
# 1) #%% (standard cell separator)
# 2) # %% (standard cell separator, when file has been edited with Eclipse)
# 3) # <codecell> (IPython notebook cell separator)

#### Cell heirarchy
# To nest navigable sections within a cell, use "#### ~some heading~"
# To nest subcells within a cell, use "#%% >> #%%% >> #%%%% .... "

In Outline Explorer (Spyder) appears as:

File.py
  % Notes
    # Section 1
    # Section 2

Example 2 : Cell with subcells

#%% Main cell

#%%% Nested cell 1
#%%%% Nested(2) cell 1
#%%%% Nested(2) cell 2

#%%% Nested cell 2

Using this structure, the nested cells can be executed separately.

File.py
  % Main Cell
    % Nested cell 1
      % Nested(2) cell 1
      % Nested(2) cell 2
    % Nested cell 2
rahul-ahuja
  • 1,166
  • 1
  • 12
  • 24