I'm aware of the %load
function (formerly %loadpy
) which loads the contents of a file (or URL, ...) into a new input cell (which can be executed afterwards).
I'm also aware of %less
, %more
and %pycat
, which show the contents of a file in a pager (which means in the notebook it's shown in the split-window at the bottom of the screen).
Is there a (magic) command to load a file and show its content (with syntax highlighting) in an output cell?
I.e. something like the following but with syntax highlighting of the result:
with open('my_file.py', 'r') as f:
print(f.read())
I want the file content to be stored with the .ipynb file but I don't want it to be executed when I do Cell -> Run All.
Is there a command similar to %psource
which shows the source code in an output cell instead of a pager?
load python file in jupyter notebook A text file can be loaded in a notebook cell with the magic command %load. the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.
py file from jupyter? Some simple options: Open a terminal in Jupyter, run your Python scripts in the terminal like you would in your local terminal. Make a notebook, and use %run <name of script.py> as an entry in a cell.
Click New —> Python 3 menu item to create a new Jupyter notebook file (. ipynb file). Input below ipython code in the first cell line, then click the Run button to run it to create file abc. txt and write text data to it.
Example code based on answer by @Matt:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import IPython
with open('my_file.py') as f:
code = f.read()
formatter = HtmlFormatter()
IPython.display.HTML('<style type="text/css">{}</style>{}'.format(
formatter.get_style_defs('.highlight'),
highlight(code, PythonLexer(), formatter)))
No there is not way to do that with current magics, but it is pretty easy using pygments and returning IPython.display.HTML(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With