Auto-load a module on python startup
Asked Answered
N

5

16

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.

Niu answered 23/10, 2010 at 7:14 Comment(0)
F
4

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

Fugitive answered 23/10, 2010 at 7:17 Comment(2)
Note that iPython has since deprecated ipythonrc. The new configuration file has the same functionality (and much more), as described in their documentation.Focus
That link is dead now. See stackoverflow.com/questions/20835977 for a resolution.Illustration
A
18

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

Adulterant answered 23/10, 2010 at 7:18 Comment(2)
Thank you too! But now how can I choose two accepted answer??Niu
@rubik: @eumiro: eumiro answered first and his answer is unique and my answer works too. Accept eumiro's answer.Adulterant
U
7

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('')
Uchish answered 23/9, 2013 at 17:19 Comment(0)
F
4

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

Fugitive answered 23/10, 2010 at 7:17 Comment(2)
Note that iPython has since deprecated ipythonrc. The new configuration file has the same functionality (and much more), as described in their documentation.Focus
That link is dead now. See stackoverflow.com/questions/20835977 for a resolution.Illustration
P
2

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
Papery answered 20/3, 2019 at 16:20 Comment(0)
P
1

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
Puffer answered 23/1, 2022 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.