【问题标题】:import python model from other folder从其他文件夹导入 python 模型
【发布时间】:2020-07-23 10:38:12
【问题描述】:

我正在尝试导入 python 模块 从 pbi-> 后端->to_pbi.py 我的主要模块是 obiee->backend ->backend_migration 怎么办?

【问题讨论】:

    标签: python-3.x operating-system


    【解决方案1】:

    您可以为此使用importlib

    直接取自文档:

    文件夹结构:

    ├── bar
    │   ├── __init__.py
    │   └── module_bar.py
    └── foo
        ├── __init__.py
        └── module_foo.py
    
    $ cat bar/__init__.py
    from . import module_bar
    
    $ cat bar/module_bar.py
    
    def run():
        print("module_bar imported")
    
    
    $ cat foo/module_foo.py
    import importlib.util
    import sys
    
    def load_module():
        fn = "custom"    
        fp = "/home/../bar/__init__.py"
        spec = importlib.util.spec_from_file_location(fn,fp)
        module = importlib.util.module_from_spec(spec)
        sys.modules[spec.name] = module
        spec.loader.exec_module(module)
        return module
    
    print(load_module().module_bar.run())
    
    $ python3.8 foo/module_foo.py
    module_bar imported
    

    【讨论】:

      猜你喜欢
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2021-01-24
      • 2022-07-16
      • 1970-01-01
      • 2018-10-13
      • 2013-08-26
      相关资源
      最近更新 更多