无法从兄弟目录导入模块

时间:2015-09-25 21:26:00

标签: python python-3.x import

我有一个Python 3项目,其结构如下:

class POI {
    private $latitude;
    private $longitude;
    public function __construct($latitude, $longitude) {
        $this->latitude = deg2rad($latitude);
        $this->longitude = deg2rad($longitude);
    }
    public function getLatitude() return $this->latitude;
    public function getLongitude() return $this->longitude;
    public function getDistanceInMetersTo(POI $other) {
        $radiusOfEarth = 6371000;// Earth's radius in meters.
        $diffLatitude = $other->getLatitude() - $this->latitude;
        $diffLongitude = $other->getLongitude() - $this->longitude;
        $a = sin($diffLatitude / 2) * sin($diffLatitude / 2) +
            cos($this->latitude) * cos($other->getLatitude()) *
            sin($diffLongitude / 2) * sin($diffLongitude / 2);
        $c = 2 * asin(sqrt($a));
        $distance = $radiusOfEarth * $c;
        return $distance;
    }
}

/project __init__.py /models __init__.py my_model.py base_model.py /tests __init__.py test.py 我要导入test.py。我的第一次尝试是my_model,它投了一个from models import my_modelThis question建议在每个目录中添加ImportError: No module named 'models'文件,但没有帮助。 Another post说要修改路径:

__init__.py

但是当import sys; import os sys.path.insert(0, os.path.abspath('..')) 尝试从my_model导入时,会引发错误。

这看起来非常简单,但我很难过。有没有人有任何想法?

3 个答案:

答案 0 :(得分:1)

在任何地方使用绝对导入:from project.models import my_model,应该可以在项目的任何地方正常工作,也不需要弄乱路径。

答案 1 :(得分:1)

将同级目录添加到sys.path应该有效:

import sys, os
sys.path.insert(0, os.path.abspath('../models'))
import my_model

答案 2 :(得分:1)

答案取决于你如何启动test.py. 我知道做相对导入的唯一方法是将文件放在包中。对于Python解释器,要知道你在一个包中是以某种方式导入它。

使用:

from ..models import my_model

在test.py中

在项目文件夹下面启动Python Interpreter。

然后您可以无错误地导入project.tests.test。

相关问题