Cell mode in Python editors - python

In recent versions of MATLAB, one can execute a code region between two lines starting with %% using Ctrl-Enter. Such region is called a code cell, and it allows for fast code testing and debugging.
E.g.
%% This is the beginning of the 1st cell
a = 5;
%% This is the end of the 1st cell and beginning of the 2nd cell
% This is just a comment
b = 6;
%% This is the end of the 2nd cell
Are there any python editors that support a similar feature?
EDIT: I just found that Spyderlib supports "block" execution (code regions separated with blank lines) with F9, but as the this thread mentions, this feature is still not very robust (in particular in combination with loops).

The Interactive Editor for Python IEP has a Matlab-style cell notation to mark code sections (by starting a line with '##'), and the shortcut by default is also Ctrl+Enter:
## Cell one
"""
A cell is everything between two commands starting with '##'
"""
a = 3
b = 4
print('The answer is ' + str(a+b))
## Cell two
print('Hello World')

Spyder3 defines a cell as all code between lines starting with #%%.
Run a cell with Ctrl+Enter, or run a cell and advance with Shift+Enter.

Spyder3 & PyCharm: #%% or # %%
Spyder3: Ctrl+Enter: to run current cell, Shift+Enter: to run current cell and advance.
PyCharm: Ctrl+Enter: to run and advance
# %%
print('You are in cell 1')
# %%
print('You are in cell 2')
# %%
print('You are in cell 3')
enter image description here

I have written a vim plugin in which cells are delimited by ## . It sends cells to an ipython interpreter running in tmux. You can define key mappings to execute the current cell, execute current cell and move to next or execute the current line :
https://github.com/julienr/vim-cellmode
I recently started working on a similar plugin for Intellij PyCharm. It can send the cell to either the internal python console (which has some issues with plots) or to an ipython interpreter running in tmux :
https://github.com/julienr/pycharm-cellmode

Pyscripter supports block execution. But it's Win only. And it's limited to select code block - > run it(Ctrl+F7). No notion of cells.

IDLE with IdleX has support for Matlab-like and Sage-like cells using SubCodes. Code in between '##' markers can be executed with Ctrl+Return. It also allows for indented markers so that indented code can be executed.

There is Sage that offers something like this. It is meant to be a python alternative to Matlab, you should take a look.
In a sage notebook, you write python commands within blocks that are pretty similar to matlab's cell.

Related

Multiple Cells in One Loop Jupyter Notebook

I have multiple codes written in different cells in jupyter notebook. The first cell contains the file name on which I need to perform the task. I am facing difficulty in running loop in jupyter notebook as I want to perform operation file by file. i.e. first take file1 to go through all the cells and then come back to lookout for file2 and so on.
I know a similar question has been asked Link1 but I am not sure how it can be done in jupter as I know in spyder we can indent in for loop and it'll run till we complete all the task then it jumps to another one but here in jupyter it seems difficult as it's cell by cell operation.
Cell 1 file_names = ['file1','file2','file3']
Cell 2 a = []
Cell 3 for file in file_names:
a.append(file)
Your distribution of code to the cells is fine (i.e. it is one possibility out of many).
You define variables in cells 1 and 2 and execute the loop in cell 3. Your file processing takes place only in cell 3.
Of course, every cell must contain valid python syntax (as must a script opened in spyder). This means the body of the for-loop must be correctly indented.

Shortcut to creating a jupyter cell in a non-notebook python file in vscode

This might be the dumbest question here but I remember there being a 3 character string which would declare a jupyter cell in a non-notebook python file in vscode and I can't seem to recall what it was and nothing ive tried so far gives a search engine result, I remember it being ## pls help
If you want to create a ipynb cell in a .py file it needs to look like this:
some code
....
....
# %%
text = "this code is now in a cell and can be run on it's own"
print(text)
# %%
# add another '# %%' before the rest of the code in your .py file so the cell above is isolated and can be run on it's own without running the rest of the program
more code
...
...
...

How to display a line for every python cell boundary in Visual Studio Code?

In VS Code, when working with python files, if we type #%% it creates a cell separation. When the cursor is within a cell, the editor displays a thick line for the top boundary and a thin line for the bottom boundary (of the current cell only). How can I change the style so that a line is always displayed for every cell boundary (like in the Spyder editor)?
Edit:
I found these settings but they only apply to the interactive window and not the editor:
"workbench.colorCustomizations": {
"notebook.cellBorderColor": "#ff0000",
"notebook.cellToolbarSeparator": "#00ff00"
}
I am expecting to find a way of showing lines at the red arrows below:
I have seen screenshots showing such lines but I can't find how.
Edit 2: Is there a way to customize the style/appearance of every inserted line showing the clickable commands Run Cell | Run Above | Debug Cell ?
take a look at this: extension-visualstudio
maybe we need to checkout [vscode-python] (https://github.com/microsoft/vscode-python): package.nls.json stores a lot of dicts, but i can't find Run Cell | Run Above | Debug Cell too..
As a possible hack, you can extend the cell commands.
The setting for that is called "Jupyter: Code Lenses".
I set mine to:
"jupyter.runcell, jupyter.runallcellsabove, jupyter.debugcell,
jupyter.debugcell, jupyter.debugcell, jupyter.debugcell,
jupyter.debugcell, jupyter.debugcell, jupyter.debugcell,
jupyter.debugcell, jupyter.debugcell, jupyter.debugcell"
long cell command list to mimic a cell border
Jupyter is a good choice for you which has separate code cells.
Create jupyter notebook from command palette then install required module ipykernal, you can run python code cell in it. Reference: Jupyter Notebook in VS Code.

Line numbers for every cell in VSCode Jupyter Notebook Cells

In the normal Jupyter notebooks, we can add line numbers by pressing the L key after selecting the cell. All the subsequent cells for that notebook will have line numbers automatically.
But this is missing in VSCode. Every time a new cell is created, we need to select the cell and press the L key to enable the numbering for that cell which is very tiresome.
Is there a way to automatically enable line numbering for all the cells in the VSCode Jupyter notebook instead of manually pressing the L key for each and every cell?
Thank you.
In VS Code Jupyter Notebook, you can toggle line numbers by pressing L. The trick is to select the current cell first.
You could select your cell by clicking in the blank area on the left margin of the cell (when it's selected the bar on the left turns blue). Now if you press L on your keyboard, you would be able to turn the line numbers on/off.
In order to toggle on/off showing the line number for all the cells(code):
Click on the blank area (left side of the cell).
Press Shift + L.
As of 2021-01-04, this is sadly not possible.
Subscribe to the GitHub issue (Feature Request) Line Numbers - All Cells #1593 for updates.
Related: Line numbers should be enabled for current cell and subsequent cells when turned on #1659
Adding to this as still comes out the top result for the problem without a proper solution.
Assuming you have the Jupyter Notebook extensions installed for VSCode, in version 1.62.3, you can go into the Settings (Ctrl+,) search for "line numbers" and find the option for "Notebook:Line Numbers" and toggle this on.
This will show line numbers for all code cells in the Notebook by default so no need to keep pressing L
screen shot of Notebook line number toggle option
I always try any combination with modifiers keys.
Found out that pressing Shift + L enables the lines number for all the notebook at once
There is an unbound command to toggle line numbers:
notebook.cell.toggleLineNumbers
BTW, beginning in v1.75 the setting
notebook.lineNumbers can show relative line numbers
VS Code can now use all editor line number options when notebook.lineNumbers is turned on. For example, with "notebook.lineNumbers": "on" and "editor.lineNumbers": "relative", relative line numbers are displayed in cell editor.
from v1.75 Release Notes: Cell Editor Polish
You can now temporarily toggle the line numbers of a cell in the
current session from the cell toolbar, or change the visibility of
line numbers for all notebooks through the notebook.lineNumbers
setting.
Under the ... in the floating menu is a line number toggle. [The gif is too large for SO.]
I tried CTRL + A (outside cells): select all cells and right clicked "show cell line number". It displayed line number for every cell.
As for 2022:
In the upper left corner, select the config-weel.
One of the options you can choose is 'Show Notebook Line Numbers'
Sweet and easy.enter image description here
Adds example for #mark answer, you can enable for current work space using:
Make new folder name .vscode
Make a setting file inside that folder called settings.json
Copy paste code in the bottom of this post.
{
// other setting can be placed here
"notebook.lineNumbers": "on"
}
Edit:
To open settings.json without manually creating the file is by opening workspace or user settings:
open Command Palette (Ctrl+Shift+P)
Type Preferences: Open User Settings (JSON) or Preferences: Open Default Settings (JSON)
Copy paste the snippet setting.
Enter empty space on Jupiter notebook .ipynb file
Click:
F1
Then write:
Show Cell File Numbers

How to embed Markdown in a python file used as a jupyter notebook in PyCharm

I prefer to create/edit jupyter notebooks directly within python using #%% cell delimiters. PyCharm is perfectly happy to identify the cells in this manner. But how do we specify that a cell is a non-python specifically markdown?
Is there something similar to code fences e.g.
#%% {markdown}
Or is there a completely different construct available for this support?
You can use the #%% md flag. For example:
#%% md
Normal Text
Other formats include:
#%% md
# Title
## Heading 1
### Heading 3
### _Bold_
### *Italics*
If you use three single quotes (or three double quotes) python will interpret everything between as literal text, including carriage returns, spaces, and ignoring what it would normally recognize as special characters.
So, you can embed markdown in a file, or in a script this way...
s = '''
This line starts at the edge and has a carriage return
This one starts two spaces in.
# This one has a hashtag, which is nŃOT seen as a comment.
https://thisIsJustTextNow.com
'''
print(s)
OUTPUT:
This line starts at the edge and has a carriage return
This one starts two spaces in.
# This one has a hashtag, which is NOT seen as a comment.
https://thisIsJustTextNow.com
I think jupytext is going to be the way to go: seems to be popular and supported. I still don't have it working perfectly but it has more promise.
pip3 install jupytext
jupytext --to notebook /git/prdnlp/python/readct.py
jupyter-notebook /git/prdnlp/python/readct.ipynb
The markdown cell is denoted as
#%% [markdown]
So the code now looks like:
#%%
import pandas as pd
from pandasql import sqldf
#%% [markdown]
"""
## Clinical Trials Postgres queries
We are using data from [ClinicalTrials.gov](https://clinicaltrials.gov/ct2/results?term=recurrent&cond=Glioblastoma+Multiforme&age_v=&gndr=&type=&rslt=With&Search=Apply)
- The data is synced to the AACT database daily
- The conditions and interventions are identified within specific tables
"""
#%%
ct = pd.read_csv('~/Downloads/SearchResults.tsv',delimiter='\t')
ctIdsDf = sqldf("select `NCT Number` nct_id, * from ct order by 1")
ctIds = ctIdsDf['nct_id']
#%%
Notice that the triple quotes do still show up in the output: so I'm unclear as to how to get them to be "stripped" out by the jupytext:

Categories

Resources