执行此操作的正常方法是简单地编写一个 python 函数,使用def
. 但是如果你想给一个语句起别名,而不是一个函数调用,那么它实际上有点棘手。
您可以通过编写自定义魔术函数来实现这一点。这是一个示例,它在 REPL中有效地将import
语句别名为 。get
from IPython.core.magic_arguments import argument, magic_arguments
@magic_arguments()
@argument('module')
def magic_import(self, arg):
code = 'import {}'.format(arg)
print('--> {}'.format(code))
self.shell.run_code(code)
ip = get_ipython()
ip.define_magic('get', magic_import)
现在可以执行get
别名为语句的import
语句。
演示:
In [1]: get json
--> import json
In [2]: json.loads
Out[2]: <function json.loads>
In [3]: get potato
--> import potato
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<string> in <module>()
ImportError: No module named potato
In [4]:
当然,这可以扩展到任意 python 代码,并且也支持可选参数。