Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Load module by its name

I'm working on a django project that serves multiple sites; depending on the site I want 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?

like image 929
Bernhard Vallant Avatar asked Dec 08 '22 02:12

Bernhard Vallant


1 Answers

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
like image 54
mykhal Avatar answered Dec 24 '22 16:12

mykhal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!