绝对导入
直接从当前模块进行导入包
# 下面是导入的自己写的类
from spatial_func import distance, SPoint
from mbr import MBR
from map_matching.candidate_point import CandidatePoint
from spatial_func import cal_loc_along_line
相对导入
主要是使用.或…等进行目录的锁定
from .spatial_func import distance, SPoint
from .mbr import MBR
from ..map_matching.candidate_point import CandidatePoint
from .spatial_func import cal_loc_along_line
报错源码
G:\githubuse\DeepMG-nbhd_dist>python tptk/main.py --phase 1 --conf_path ./data/conf_tdrive_sample.json --results_path ./data/tdrive_sample/results/
Traceback (most recent call last):
File "tptk/main.py", line 3, in <module>
from common.trajectory import Trajectory, store_traj_file, parse_traj_file
File "G:\githubuse\DeepMG-nbhd_dist\tptk\common\trajectory.py", line 4, in <module>
from ..map_matching.candidate_point import CandidatePoint
ValueError: attempted relative import beyond top-level package
类似报错
ValueError: attempted relative import beyond top-level package
# 翻译:试图在顶级包之外进行相对导入
ImportError: attempted relative import with no known parent package
# 翻译:尝试相对导入,但没有已知的父包
ValueError: Attempted relative import in non-package
# 翻译:试图在非包中进行相对导入
SystemError: Parent module '' not loaded, cannot perform relative import
# 翻译:父模块'xxx'未加载,不能执行相对导入。
解决方法
最简单的是将当前模块设置为root,然后在该模块中使用绝对导入。
如下,我将tptk设置为Sources Root。
在其中某个文件中的引用,其中的map_matching和common均为tptk模块的第一层子目录
from map_matching.hmm.hmm_probabilities import HMMProbabilities
from map_matching.hmm.ti_viterbi import ViterbiAlgorithm, SequenceState
from map_matching.map_matcher import MapMatcher
from map_matching.candidate_point import get_candidates
from common.spatial_func import distance
from common.trajectory import STPoint, Trajectory
from map_matching.utils import find_shortest_path
from map_matching.route_constructor import construct_path