繁体   English   中英

python 从不同级别目录导入找不到模块

[英]python import from different level directory no module find

python 从不同级别的目录导入得到导入错误

目录结构。

# all __init__.py files are empty



import/
├── helpers
│   ├── __init__.py
│   ├── helper1
│   │   ├── __init__.py
│   │   ├── helper1_module1.py
│   │   └── helper1_module2.py
│   └── helper2
│       ├── __init__.py
│       ├── helper2_module1.py
│       └── helper2_module2.py
└── services
    ├── __init__.py
    ├── service1
    │   ├── __init__.py
    │   └── service1_api.py
    └── service2

helper1_module1.py

class Helper1Module1():
    def function1(self):
        print("executed from Helper1Module1 Class function1")

    def function2(self):
        print("executed from Helper1Module1 Class function2")

service1_api.py

from helpers.helper1.helper1_module1 import Helper1Module1

h = Helper1Module1()
h.function1()

错误:

python3 services/service1/service1_api.py 
Traceback (most recent call last):
  File "services/service1/service1_api.py", line 1, in <module>
    from helpers.helper1.helper1_module1 import Helper1Module1
ModuleNotFoundError: No module named 'helpers'

如何解决这个问题?

Python:python3.6及以上操作系统:Linux

您必须手动设置文件路径 (PYTHONPATH) 才能使用其他目录中的文件。

您可以导出环境变量,如

导出 PYTHONPATH='路径/到/目录'

或者你可以使用 sys 模块: Importing files from different folder

暂无
暂无

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

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