Using VSCode to run a Python file with Jupyter notebook cells

To run a Python file with Jupyter notebook cells using Visual Studio Code (VSCode), you can follow these steps:

  1. Install the necessary extensions:
  • Python: Install the "Python" extension from Microsoft for Python development in VSCode.
  • Jupyter: Install the "Jupyter" extension from Microsoft to work with Jupyter notebooks in VSCode.
  1. Create a new Python file:
  • Open VSCode and create a new Python file by clicking on "File" > "New File" or using the shortcut (Ctrl+N).
  • Save the file with a .py extension, for example, my_script.py.
  1. Add Jupyter notebook cells:
  • In the Python file, you can add Jupyter notebook cells using the #%% marker. It's a special comment that defines a cell.
  • Each cell can contain Python code snippets that you want to execute individually. Here's an example of a Python file with Jupyter notebook cells:
#%%
print("This is cell 1")

#%%
print("This is cell 2")

#%%
print("This is cell 3")

Alternatively…

#In[1]:
print("This is cell 1")

#In[2]:
print("This is cell 2")

#In[3]:
print("This is cell 3")
  1. Run Jupyter notebook cells:
  • To run the Jupyter notebook cells in the Python file, you can use the VSCode's Run Cell feature provided by the Jupyter extension.
  • Place the cursor inside a cell or select the cell you want to run.
  • To run a single cell, you can use the shortcut (Shift+Enter) or right-click and choose "Run Cell" from the context menu. Or, I like to use (Ctrl+Enter) to run and stay on the same cell.
  • To run all the cells in the file, right-click to run in interactive window, and choose run all cells. When you run a cell, the output will be displayed in the integrated VSCode terminal. If you have any print statements or code that produces output, you will see it in the terminal.

Note: VSCode treats each Jupyter notebook cell as a separate block of code, so you can execute them individually or all together. It provides a convenient way to organize and test your code in a notebook-like format within a Python file.