I'm working on a django project that serves multiple sites; depending on the site I w开发者_运维知识库ant to import different functionality from a different module; how do I import a module in Python if I have the name of its package and the module name itself as a string?
in Python generally, you can use __import__ builtin function or imp module features:
>>> sys1 = __import__("sys")
>>> import imp
>>> sys2 = imp.load_module("sys2", *imp.find_module("sys"))
>>> import sys
>>> sys is sys1 is sys2
True
Django has its own import function to get an objet from a string. From documentation:
django.utils.module_loadingFunctions for working with Python modules.
import_string(dotted_path)Imports a dotted module path and returns the attribute/class designated by the last name in the path. Raises ImportError if the import failed. For example:
from django.utils.module_loading import import_string ValidationError = import_string('django.core.exceptions.ValidationError')is equivalent to:
from django.core.exceptions import ValidationError
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论