![](/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.