在import命令中使用变量 [英] using variable in import command

查看:149
本文介绍了在import命令中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,如

k = os

如果我必须进口os
我可以写

If I have to import os I can write

import os

然后我没有错误
但我怎样才能导入k(k是实际上 os
我试过

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

import k

然后我得到错误,没有模块。
我尝试命名 k ='os'而不是 k = os 。但是我得到的相同错误

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

更新:
实际上我必须从导入DATABASES 变量来自环境变量DJANGO_SETTINGS_MODULE中的设置文件

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

如何实现此目的

from os.environ['DJANGO_SETTINGS_MODULE'] import DATABASES


推荐答案

使用 importlib 模块,如果你想根据字符串导入模块:

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'>

当你这样做时:

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

然后Python仍然查找名为 k.py k.pyc 等不是 os.py 如你所愿。

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

这篇关于在import命令中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆