问题
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