Data Science Asked by Manu H on March 13, 2021
I’m currently working/prototyping into a Jupyter notebook. I want to run some of my code on a standalone iPython shell.
For now, I export my iPython code (file –> download as) and then execute it in my iPython (with %run). It works, but I would like to export only one cell or set of cells. So, that I can run only what I modified in my Jupyter notebook.
I am not sure if it is possible to export only one cell in Jupyter notebooks.
But I do know that you could download as a python file and simply copy paste the particular cell you want in your new Jupyter notebook.
Let me know if you need any more help!
Answered by Chase Kregor on March 13, 2021
You can use %%capture Jupyter notebook' magic command to catch output of cell and then paste it to your text file with
with open('output.txt', 'w') as out:
out.write(cap.stdout)
if you want to cell code to specific file for example code.txt you can use magic function %%writefile
%%writefile example.txt
ab = 'This is code'
a = 5
print(a+ 2)
Also if you want to append to file you must use -a parameter
Answered by user38487 on March 13, 2021
One way this can be done is to use Python's output caching system to access the output of a cell so it can be saved off to a file. The output from a numbered cell x is stored in a variable named _x
, and output from the last command is in _
etc. e.g. Save the output of cell number 10 to a file cell_10.pickle
using python's pickle format:
import pickle
with open('cell_10.pickle', 'wb') as f:
pickle.dump(_10, f, pickle.HIGHEST_PROTOCOL)
Answered by Pierz on March 13, 2021
You can register a new cell magic, for example:
from IPython.core.magic import register_cell_magic
@register_cell_magic
def run_and_save(line, cell):
'Run and save python code block to a file'
with open(line, 'wt') as fd:
fd.write(cell)
code = compile(cell, line, 'exec')
exec(code, globals())
Now, you can use the run_and_save magic:
%%run_and_save hello.py
class Hello:
def __init__(self):
pass
Answered by David Chen on March 13, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP