How to dynamically import a module in Python
本问题已经有最佳答案,请猛点这里访问。
我正在尝试根据文件名导入文件,例如:
1 2 3 4 5 6 7 | project / __init__.py log.py conf / __init__.py logger_settings.py other_settings.py |
在我的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab import os import sys import json def get_settings(identity): """Settings.""" try: from i import * except ImportError as exc: raise Exception('Eror importing config %s' % exc) |
因此,比起在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/env python -u # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab import os import logging from project import conf CONF = conf.get_settings('logger_settings') def getLogger(identity ,log_file=CONF.log_file): # Then access CONF to return settings # For example: # host = CONF.host would return something like 'localhost' |
我想让
1 2 | log_file = '/mnt/logs/' host = 'localhost' |
为了实现这一点,我需要如何修改
见
它们提供了一种动态导入模块的方法(即,其名称由运行时值给出)。
1 2 | import importlib settings = importlib.import_module('conf.%s' % i) |
- http://docs.python.org/dev/library/importlib.html
- http://docs.python.org/2/library/functions.html网站