'How can I write an IPython cell magic command that runs the code in the cell?
I have written a cell magic for a program I am writing where I want to save the cell to a python file, but I would ideally also want to run the code in the cell so I can use them later in the notebook.
Magic Code
# custom_magic.py
from pathlib import Path
from IPython.core.magic import register_cell_magic
@register_cell_magic
def service_cell(project_dir, cell):
project_dir = Path(project_dir)
project_dir.mkdir(parents=True, exist_ok=True)
with open(project_dir / "service.py", "w") as file_handle:
file_handle.write(cell)
In the notebook:
from custom_magic import service_cell
%%service_cell notebook_service
def echo(msg: str) -> str:
return msg
echo("hello")
Output:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-b1e6d0cc609b> in <module>
----> 1 echo("helo")
NameError: name 'echo' is not defined
Solution 1:[1]
You need to add the following at the start and end of your magic method
from IPython import get_ipython
....
get_ipython().run_cell(cell)
your magic should looks like this
# custom_magic.py
from IPython import get_ipython
from pathlib import Path
from IPython.core.magic import register_cell_magic
@register_cell_magic
def service_cell(project_dir, cell):
project_dir = Path(project_dir)
project_dir.mkdir(parents=True, exist_ok=True)
with open(project_dir / "service.py", "w") as file_handle:
file_handle.write(cell)
get_ipython().run_cell(cell)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zee |
