using variable in import command

2019-01-12 04:00发布

I have a variable like

k = os

If I have to import os I can write

import os

then I get no error But how can I import k ( k is actually os ) I tried

import k

then I got error there is no module. I tried naming k = 'os' instead of k = os.Still I am getting the same error

Update : Actually I have to import DATABASES variable from settings file in the environmental variable DJANGO_SETTINGS_MODULE

How can I achieve this

from os.environ['DJANGO_SETTINGS_MODULE'] import DATABASES

2条回答
疯言疯语
2楼-- · 2019-01-12 04:45

Use importlib module if you want to import modules based on a string:

>>> import importlib
>>> os = importlib.import_module('os')
>>> os
<module 'os' from '/usr/lib/python2.7/os.pyc'>

When you do something like this:

>>> k = 'os'
>>> import k

then Python still looks for file named k.py, k.pyc etc not os.py as you intended.

查看更多
唯我独甜
3楼-- · 2019-01-12 04:55

You can use the __import__ function:

k = 'os'
module = __import__(k)
查看更多
登录 后发表回答