如何使用python从同级子目录导入

时间:2019-04-04 05:48:33

标签: python import

- folder container
     - folder build
         - build.py

     - folder uni
         - folder build-server
             - RemoteInterface.py

问题:如何从build.py导入RemoteInterface?鉴于文件夹“ build”和“ build-server”没有 init .py

我尝试-

from ..uni.build_server.RemoteInterface import RemoteInterface 

# - shows  attempted relative import beyond top-level package
from ..uni.build-server.RemoteInterface import RemoteInterface 

#- shows syntax error at build-server (for the hyphen)

也显示类似的错误:

from ...uni.build_server.RemoteInterface import RemoteInterface 


from ...uni.build-server.RemoteInterface import RemoteInterface 

期望从build.py成功导入RemoteInterface

1 个答案:

答案 0 :(得分:0)

目录树:

.
├── build
│   └── build.py
└── uni
    ├── build-server
    │   └── RemoteInterface.py
    └── buildserver
        └── RemoteInterface.py
  1. uni/build-server/RemoteInterface.py
RemoteInterface = "build-server"
  1. uni/buildserver/RemoteInterface.py
RemoteInterface = "buildserver"
  1. build/build.py
from __future__ import absolute_import
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from importlib import import_module
from uni.buildserver import RemoteInterface


import_module("uni.build-server.RemoteInterface")
_RemoteInterface = sys.modules["uni.build-server.RemoteInterface"]

print(RemoteInterface.RemoteInterface)
print(_RemoteInterface.RemoteInterface)
  1. 输出:
buildserver
build-server

注意:尝试不要出现在目录名称-