python – Run indented code through keyboard shortcuts in Spyder as in RStudio

Question:

I would like to be able to run an indented block of code in python in the same way I do in R. In particular, if in RStudio I have the following indented block of code:

print(seq(from = 1,
          to = 10,
          by = 1))

I can place the cursor everywhere (at the beginning of the code, in the middle, at the end) except in a new line below and simply press Cmd+Enter (or Ctrl+Enter) and I can run such code.

However, in Spyder 4.2, a similar code like this one:

import pandas as pd

cars = {'Brand': ['Honda', 'Ford','Audi'],
        'Price': [20000, 30000, 40000]}

will not run wherever I place the cursor, and I have to select the two lines to create the dataframe and launch the whole selection with Cmd+Enter (I modified the keyboard shortcuts in the preferences of Spyder to run a selection).

Any advice on how to run such code without selecting it first? Thanks!

Asked By: nd091680

||

Answers:

(Spyder maintainer here) You said

Any advice on how to run such code without selecting it first?

Yes, you need to use cells for that. You can create a cell by inserting a comment that starts with # %%, like this

import pandas as pd

# %%
cars = {'Brand': ['Honda', 'Ford','Audi'],
        'Price': [20000, 30000, 40000]}

That will allow you to run the piece of code enclosed by those comments with the keyboard shortcuts Shift + Enter (run current cell and advance to the next one); or Control + Enter (run current cell and stay on it).

If that explanation was not clear enough, you can learn more about cells in our docs.

Answered By: Carlos Cordoba

This would be absolutely fantastic if it worked, but it doesn’t. I’m guessing there must be a setting that needs to be changed first that everyone fails to mention

Answered By: JohnScone