繁体   English   中英

在 python 启动时自动加载模块

[英]Auto-load a module on python startup

我希望 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文件。 在每一行上, *.pth文件应包含要包含在sys.path的路径或要执行的命令。 该模块还可以导入sitecustomizeusercustomize (如果它们存在于sys.path某个位置,则可以包含任意代码,一种让同事发疯的好方法,如果它们碰巧会出现错误)。

但问题是,当导入site模块时,当前目录不在sys.path ,即配置特定脚本很困难。

我有时会在脚本的开头添加以下行,以便脚本从searchin查找当前目录中的.pth文件并将缺少的路径添加到sys.path

# search for *.pth files in the current directory
import site; site.addsitedir('')

检查文件~/.ipython/ipythonrc - 您可以列出要在启动时加载的所有模块。

另一种可能的解决方案是使用python解释器的参数-i它在执行脚本后启动交互模式。

你可以使用例如:

  • 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM