簡體   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