IPython - importing/populating namespace with custom magic

北战南征 提交于 2019-12-11 11:27:22

问题


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
    """

It then should be possible:

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:


Advice 1: Don't use %pylab.

Advice 2: don't try to imitate pylab usage it will bite you

If you want to have convenient import create your own package and do from mypackage import *

If you really want a magic that have access to python namespace you should see this question. and add the @needs_local_scope decorator.



来源:https://stackoverflow.com/questions/28698045/ipython-importing-populating-namespace-with-custom-magic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!