简体   繁体   English

在 python3 中动态导入模块 - 问题

[英]Dynamically importing module in python3 - issue

In a project, I want to dynamically import the right module based on a version-number.在一个项目中,我想根据版本号动态导入正确的模块。 For this I'm using importlib, and works find as long as the package is part of the source.为此,我使用 importlib,只要 package 是源代码的一部分,就可以找到工作。

AdminApi = import_module(f"{self.version}", "AdminApi").AdminApi

The folder-structure looks like:文件夹结构如下所示:

Admin-Package / 
    - __init__.py  # Contains dynamic class loader
    - admin64/
        - __init__.py  # contains AdminApi v6.4
        - ...
    - admin65/...
        - __init__.py  # contains AdminApi v6.5
        - ...

However, now I find myself needing to decouple the code into its own package to re-use in another project.但是,现在我发现自己需要将代码解耦到它自己的 package 中,以便在另一个项目中重复使用。 So I've packaged this part of the source.所以我把这部分源码打包了。 This however seems to cause path-related issues.然而,这似乎会导致与路径相关的问题。 This seems to mean that importlib cannot help me.这似乎意味着 importlib 无法帮助我。

So far, thanks to: https://stackoverflow.com/a/54138717/5731101 I've come to this point:到目前为止,感谢: https://stackoverflow.com/a/54138717/5731101我已经到了这一点:

import importlib
from pathlib import Path

path = Path(__file__).resolve().parent
script_path = os.path.join(path, version, '__init__.py')

spec = importlib.util.spec_from_file_location(f"AdminApi", script_path)
AdminApi = importlib.util.module_from_spec(spec)
spec.loader.exec_module(AdminApi)

Unfortunately the spec.loader.excec_module fails with error: ModuleNotFoundError: No module named 'AdminApi' Even thought the class is clearly available in the file supplied via the path.不幸的是, spec.loader.excec_module失败并出现错误: ModuleNotFoundError: No module named 'AdminApi'即使 class 在通过路径提供的文件中清楚地可用。

I would be grateful if anyone can help me out on this.如果有人能帮助我解决这个问题,我将不胜感激。

I decided to try another tool in the toolbox of importlib Based on this answer: https://stackoverflow.com/a/67692/5731101我决定在 importlib 的工具箱中尝试另一个工具基于这个答案: https://stackoverflow.com/a/67692/5731101

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("AdminAPI", "/path/to/file.py").load_module()
foo.AdminAPI()

This approach had no problems detecting the class and simply imported everything correctly.这种方法检测 class 没有问题,只需正确导入所有内容。

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

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