3

I'm using python on Windows. And I'm trying to find a way to import some default module when starting python. It means, when starting python, some modules should be already imported, just like builtins. Is there any way?

Thanks.

3 Answers3

5

If you mean while going into the interactive mode, just make a small startup script. Instead of just launching python with:

python

try instead:

python -i startupImports.py

startupImports.py:

import time
from collections import defaultdict
from customclass import myclass
#...etc
gregb212
  • 799
  • 6
  • 10
3

Define a PYTHONSTARTUP environment variable and point it to a python file and it will be loaded when you start python interactively without a command line script.
I have my PYTHONSTARTUP point to a .pythonrc where I try to import a __boot__.py (bootstrap) in the current directory for any interactive python session.

try:
    from __boot__ import *
except Exception:
    pass

There's a bunch of other things in my pythonrc like __future__ imports, readline setup, etc.

AChampion
  • 29,683
  • 4
  • 59
  • 75
1

One option is adding your import to sitecustomize.py. This file is automatically imported at startup. This will be loaded whether Python is started in interactive mode or not. To quote the docs:

[In site.py] an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. It is typically created by a system administrator in the site-packages directory. If this import fails with an ImportError exception, it is silently ignored.

Another option is to set the PYTHONSTARTUP environment variable to a startup script with your import. This will only be executed if Python is started in interactive mode, though.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251