我希望 IPython 或 Python 解释器在我启动它们时自动加载它们。
是否可以?
例如,当我启动 IPython 时:
$ ipython
...
>>> from __future__ import division
>>> from mymodule import *
In [1]:
类似于教程页面中的SymPy 的 live shell 。
我希望 IPython 或 Python 解释器在我启动它们时自动加载它们。
是否可以?
例如,当我启动 IPython 时:
$ ipython
...
>>> from __future__ import division
>>> from mymodule import *
In [1]:
类似于教程页面中的SymPy 的 live shell 。
在您的主目录中有一个.pythonstartup
并在那里加载模块并将PYTHONSTARTUP
env 指向该文件。
该文件中的 Python 命令在第一个提示以交互模式显示之前执行。
我用它在 python 解释器 shell 中启用命令行完成
除非-S
将选项传递给python
二进制文件,否则默认情况下会在执行传递给您的脚本或交互式解释器之前导入一个特殊的站点模块。除其他外,该模块会查找*.pth
文件。在每一行上,*.pth
文件应包含要包含的路径sys.path
或要执行的命令。如果它们存在sitecustomize
于.usercustomize
sys.path
sys.path
问题是,导入模块时当前目录不在site
,即很难配置您的特定脚本。
我有时会在脚本的开头添加以下行,以便脚本以搜索.pth
当前目录中的文件开始并将缺少的路径添加到sys.path
:
# search for *.pth files in the current directory
import site; site.addsitedir('')
检查文件~/.ipython/ipythonrc
- 您可以列出要在启动时加载的所有模块。
另一种可能的解决方案是使用来自解释器的参数-i
python
,该参数在执行脚本后启动交互模式。
例如,您可以使用:
python -i your_module.py
python -i /path/to/your/module
如果您定义了一个__main__.py
python -i -m your.module
要在使用它们时自动延迟导入所有顶级可导入模块,请在PYTHONSTARTUP
文件中定义:
import pkgutil
from importlib import import_module
class LazyModule:
def __init__(self, alias, path):
self._alias = alias
self._path = path
globals()[self._alias] = self
def __getattr__(self, attr):
module = import_module(self._path)
globals()[self._alias] = module
return getattr(module, attr)
# All top-level modules.
modules = [x.name for x in pkgutil.iter_modules()]
for module in modules:
LazyModule(alias=module, path=module)
# Also include any other custom aliases.
LazyModule("mpl", "matplotlib")
LazyModule("plt", "matplotlib.pyplot")
LazyModule("pd", "pandas")
LazyModule("sns", "seaborn")
LazyModule("tf", "tensorflow")
现在您可以访问模块而无需手动导入它们:
>>> math.sqrt(0)
0