我知道%load
函数(以前称为%loadpy
)将文件(或URL等)的内容加载到新的输入单元格中(之后可以执行)。
我也知道%less
、%more
和%pycat
,它们在寻呼机中显示文件的内容(这意味着在笔记本中它显示在屏幕底部的拆分窗口中)。
是否有(魔术)命令来加载文件并在输出单元格中显示其内容(带有语法突出显示)?
即类似于以下内容,但结果的语法突出显示:
with open('my_file.py', 'r') as f:
print(f.read())
我希望文件内容与 .ipynb 文件一起存储,但我不希望在执行 Cell -> Run All 时执行它。
是否有类似于%psource
的命令在输出单元格而不是寻呼机中显示源代码?
基于@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)))
不,使用当前的魔法没有办法做到这一点,但是使用pygments和返回IPython.display.HTML(...)
非常容易。
10年后,现在有一个更简单的解决方案:https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.Code
from IPython.display import Code
Code(filename='my_file.py', language='python')