I want to import all modules from a particular directory of a package which I installed using pip, that is, it lies in site-packages
.
What I tried
Let's say the package name is package
and it has a directory called directory
. It has many files like a.py
, b.py
, etc. I need to import all of them. I listed all files in directory
using in-built __file__
, which isn't the problem. When I tried to import the modules using importlib.import_module
, I got ModuleNotFoundError
even though I'm 100% percent sure they exist. I used relative import.
Code Snippet
modules
is the list of all files in directory
for module in modules:
importlib.import_module('.'+module, 'C:\\Users\\.....\\package\\directory')
ModuleNotFoundError: No module named 'C:\\Users\\.....\\package\\directory'
Finally
What am I doing wrong and what is the right approach to refer site-packages?
create an empty init .py file under the directory that you want Execute
import pkgutil
import sys
def load_all_modules_from_dir(dirname):
for importer, package_name, _ in pkgutil.iter_modules([dirname]):
full_package_name = '%s.%s' % (dirname, package_name)
if full_package_name not in sys.modules:
module = importer.find_module(package_name
).load_module(full_package_name)
print module
load_all_modules_from_dir('site-packages')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.