python 启动时自动加载模块

发布于 2024-09-28 14:09:43 字数 230 浏览 7 评论 0原文

我希望 IPython 或 Python 解释器在启动时自动加载模块。

是否可以?

例如,当我启动 IPython 时:

$ ipython

...

>>> from __future__ import division
>>> from mymodule import *

In [1]:

在教程页面。

I want IPython or the Python interpreter to auto-load a module when I start them.

Is it possible?

For example when I start IPython:

$ ipython

...

>>> from __future__ import division
>>> from mymodule import *

In [1]:

Something like SymPy's live shell found in the tutorial pages.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

等风也等你 2024-10-05 14:09:43

在您的主目录中有一个 .pythonstartup 并在其中加载模块,并将 PYTHONSTARTUP env 指向该文件。

在以交互模式显示第一个提示之前,将执行该文件中的 Python 命令。

我用它来在 python 解释器 shell 中启用命令行补全

Have a .pythonstartup in your home directory and load modules there and point PYTHONSTARTUP env to that file.

Python commands in that file are executed before the first prompt is displayed in interactive mode.

I use it for enabling command line completion in python interpreter shell

感受沵的脚步 2024-10-05 14:09:43

除非将 -S 选项传递给 python 二进制文件,否则会使用特殊的 site 模块。除此之外,该模块还会查找 *.pth 文件。在每一行中,*.pth 文件应包含要包含到 sys.path 中的路径或要执行的命令。该模块还导入 sitecustomizeusercustomize (它可以包含任意代码,如果他们碰巧引发错误,这是让你的同事发疯的好方法)(如果它们存在于某处)在sys.path中。

但问题是,当导入 site 模块时,当前目录不在 sys.path 中,也就是说很难配置您的特定脚本。

我有时会在脚本的开头添加以下行,以便脚本首先在当前目录中搜索 .pth 文件并将缺少的路径添加到 sys.path:

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

Unless -S option is passed to the python binary, a special site module is imported by default before the execution is passed to your script, or the interactive interpreter. Among other things the module looks for *.pth files. On each line the *.pth files should contain either a path to include into sys.path, or a command to execute. The module as well imports sitecustomize, and usercustomize (which can contain arbitrary code, a good way to make your colleagues crazy, if they happen to raise errors) if they exist somewhere in sys.path.

The problem is though, that the current directory in not in sys.path when the site module is imported, that is it is hard to configure your particular script.

I sometimes add the following line at the beginning of my scripts, so that the script would start with searchin for .pth files in the current directory and adding the missing paths to sys.path:

# search for *.pth files in the current directory
import site; site.addsitedir('')
水溶 2024-10-05 14:09:43

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

Check the file ~/.ipython/ipythonrc - you can list all modules you want to load at the startup.

森末i 2024-10-05 14:09:43

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

例如,您可以使用:

  • python -i your_module.py
  • python -i /path/to/your/module 如果您定义了 __main__.py< /code>
  • 甚至 python -i -m your.module

Another possible solution is to use the argument -i from python interpreter that launches the interaction mode after executing your script.

You could for instance use:

  • python -i your_module.py
  • python -i /path/to/your/module in case you have defined a __main__.py
  • or even python -i -m your.module
山川志 2024-10-05 14:09:43

要在使用时自动延迟导入所有顶级可导入模块,请在 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

To automatically lazily import all top-level importable modules when using them, define this in your PYTHONSTARTUP file:

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

Now you can access modules without needing to import them manually:

>>> math.sqrt(0)
0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文