Python: dynamically import module contents

I have a lot

from myproject.settings import param1
from myproject.settings import ...

scattered throughout my project.

At startup, I would like to load different “settings” according to env var (for example, export SETTINGS=myproject.settings2)

I tried to install myproject.__init__.py something like

module_name =  os.environ['SETTINGS']
m=__import__(module_name)
settings = m

but that will not work.

from myproject.settings import *
ImportError: No module named settings

How can this be achieved?

+3
source share
3 answers

Try using the dummy argument "fromlist".

mymodule = __import__(mod, fromlist=['a'])

He worked for me before in situations like yours.

+1
source
settings = __import__(os.environ['SETTINGS'])

but that will not work.

Why? Your approach is correct. As an example, Django does the same.

0
source

myproject.settings PYTHONPATH :

PYTHONPATH=$PYTHONPATH:$HOME/myproject/settings/ export PYTHONPATH

~/.bashrc( UNIX env). , , , PYTHONPATH. .. python , , .

Now, whatever path you just typed import settings, and since it is myproject/settingspresent, python will load the settings file.

Hope this helps ...

0
source

Source: https://habr.com/ru/post/1768074/


All Articles