In JupyterLab, you can run a specific Python instruction (or a set of instructions) before each cell execution using startup scripts or cell magic commands. Here are the most common and effective methods:
%run Magic CommandYou can use the %run magic command at the top of your notebook to execute a script before running any cell. However, this only runs once at the start, not before each cell.
%%capture and %automagic (Not Recommended for This Use Case)These are not directly useful for running code before each cell, but are mentioned for completeness.
You can create a startup script that runs every time a Jupyter kernel starts. This is useful for imports or configurations, but not for running code before each cell.
Create a file (e.g., startup.py) in the IPython profile startup directory:
python# Find your profile directory: !jupyter --paths
Place your script in the startup folder of your profile directory.
Add your code to startup.py. This will run when the kernel starts, not before each cell.
You can write a custom IPython extension to run code before each cell execution. This is more advanced but gives you full control.
my_extension.py:
pythondef load_ipython_extension(ipython): def pre_run_cell(info): print("Running before each cell!") # Add your code here ipython.events.register('pre_run_cell', pre_run_cell)
bashipython register my_extension.py
python%load_ext my_extension
%autorun (Not Native, Requires Custom Setup)There is no native %autorun magic, but you can simulate this behavior with a custom solution.
%%capture magic to suppress output if needed.There are third-party extensions (like jupyter-contrib-nbextensions) that allow you to run a cell automatically before others, but this is not built into JupyterLab by default.
If you want to run a specific instruction before each cell, the most practical approach is to:
Example:
pythondef setup(): print("Running setup code!") # Your setup code here setup() # Call this at the start of each cell