IPython - 使用自定义魔术导入/填充命名空间 [英] IPython - importing/populating namespace with custom magic
问题描述
IPython中的%pylab
魔法将一堆函数导入用户的工作区,这非常方便。看看这些代码,完成这项工作并不是很明显。到目前为止,我的启动文件夹中有一个神奇的功能:
The %pylab
magic in IPython imports a bunch of functions into the user's workspace, which is very convenient. Looking at the code, it's not at all obvious how this is done. What I have so far is a magic function in my startup folder:
from IPython.core.magic import register_line_magic
@register_line_magic
def import_my_functions(line):
"""
Import functions into namespace somehow....
e.g. import numpy as np
"""
然后应该可以:
In[1]: %import_my_functions
imported the following:
numpy as np
.....
In[2]: np
Out[2]: <module 'numpy' from ..../venv/lib/python2.7/site-packages/numpy/__init__.pyc'>
如果该命令还重新加载已更改的模块,则会获得奖励。
Bonus would be if the command also reloads changed modules.
推荐答案
建议1:不要使用%pylab
。
建议2:不要试图模仿pylab使用它会咬你
Advice 2: don't try to imitate pylab usage it will bite you
如果你想拥有方便导入创建自己的包并从mypackage导入 *
If you want to have convenient import create your own package and do from mypackage import *
如果你真的想要一个有权访问的魔法你应该看到python命名空间这个问题。并添加 @needs_local_scope
装饰器。
If you really want a magic that have access to python namespace you should see this question. and add the @needs_local_scope
decorator.
这篇关于IPython - 使用自定义魔术导入/填充命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!