![](/img/trans.png)
[英]How to show source code for dynamically created (“custom”) function in IPython?
[英]How to show source code of a package function in IPython notebook
出于教学目的,我想要一个IPython笔记本显示(作为单元格的输出)功能源代码,但我希望能够在多个笔记本中引用它。 因此,我希望以类似于使用%psource魔术的方式显示功能代码,但会突出显示适当的语法。
这是与此问题类似的问题,但我希望能够将其应用于文件中的单个函数,而不是一次性应用于完整文件。
使用上一个问题的建议我破解了一个简单的短代码:
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)))
两个问题:
1)Magics只是简单的功能,不难定义,你可以看看这里 Customizing IPython - Config.ipynb
如果我没记错的话。 我仍然不确定在你的情况下确定一个魔法是值得的。
2)大多数时候,没有。 您必须导入模块,因为我们需要实时代码来了解它的定义位置。
通常,找到函数的代码并不总是非常简单。 在python 3上,你总是可以访问代码对象,但大多数时候,只要你有装饰函数或动态生成函数之类的东西,它就变得很难。 我想你也可以从psource
/ pinfo2
启发并让它们返回信息而不是分页。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.