【发布时间】:2013-12-18 17:56:24
【问题描述】:
出于教学目的,我想要一个显示(作为单元格的输出)函数源代码的 IPython 笔记本,但我希望能够在多个笔记本中引用它。因此,我想以类似于使用 %psource 魔法的方式显示函数代码,但适当地突出显示语法。
这是与this question 类似的问题,但我希望能够将其应用于文件中的单个函数,而不是一次应用于整个文件。
使用上一个问题的建议,我破解了一个在简单情况下有效的短代码:
def print_source(module, function):
"""For use inside an IPython notebook: given a module and a function, print the source code."""
from inspect import getmembers, isfunction, getsource
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from IPython.core.display import HTML
internal_module = __import__(module)
internal_functions = dict(getmembers(internal_module, isfunction))
return HTML(highlight(getsource(internal_functions[function]), PythonLexer(), HtmlFormatter(full=True)))
两个问题:
- This gist 建议通过定义适当的单元魔术来显示整个功能。是否可以像上面那样定义一个适当的单元格魔术来只显示一个函数?
- 有没有一种方法可以在不导入整个模块的情况下执行此操作,或者是否有更强大的方法来执行此操作?
【问题讨论】:
标签: python ipython ipython-notebook ipython-magic