简体   繁体   English

使用 import_module 从站点包访问模块

[英]use import_module to access module from site-packages

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 .我想从我使用 pip 安装的 package 的特定目录中导入所有模块,也就是说,它位于site-packages

What I tried我试过的

Let's say the package name is package and it has a directory called directory .假设 package 名称是package并且它有一个名为directory的目录。 It has many files like a.py , b.py , etc. I need to import all of them.它有很多文件,如a.pyb.py等。我需要将它们全部导入。 I listed all files in directory using in-built __file__ , which isn't the problem.我使用内置的__file__列出了directory中的所有文件,这不是问题。 When I tried to import the modules using importlib.import_module , I got ModuleNotFoundError even though I'm 100% percent sure they exist.当我尝试使用importlib.import_module导入模块时,我得到ModuleNotFoundError即使我 100% 确定它们存在。 I used relative import.我使用了相对导入。

Code Snippet代码片段

modules is the list of all files in directory modulesdirectory中所有文件的列表

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在要执行的目录下创建一个空的init .py 文件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM