![](/img/trans.png)
[英]Is there a way to 'auto-load' python variables when you create a new script?
[英]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
的路徑或要執行的命令。 該模塊還可以導入sitecustomize
和usercustomize
(如果它們存在於sys.path
某個位置,則可以包含任意代碼,一種讓同事發瘋的好方法,如果它們碰巧會出現錯誤)。
但問題是,當導入site
模塊時,當前目錄不在sys.path
,即配置特定腳本很困難。
我有時會在腳本的開頭添加以下行,以便腳本從searchin查找當前目錄中的.pth
文件並將缺少的路徑添加到sys.path
:
# search for *.pth files in the current directory
import site; site.addsitedir('')
檢查文件~/.ipython/ipythonrc
- 您可以列出要在啟動時加載的所有模塊。
要在使用時自動延遲導入所有頂級可導入模塊,請在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.