为什么不能在我的项目中导入我自己的库?

时间:2018-01-26 21:17:23

标签: python python-import

我有一个简单的python项目。其结构如下:

C:\projects\python\Testovnik>tree
Folder PATH listing
Volume serial number is BC5F-5E5E
C:.
├───.vscode
│   └───.ropeproject
├───Testovnik
│   ├───lib
│   │   └───__pycache__
│   └───questions
└───tests

现在在tests目录中我有这个文件:

question_tests.py

import unittest

from Testovnik.lib.question import Question
from Testovnik.lib.question_file import QuestionFile

test_file = '..\\questions\\002.txt'


class TestQuestion(unittest.TestCase):
    def test_question(self):
        question_file = QuestionFile(test_file)
        self.assertEqual(question_file.get_question, 'Pisior?')

    def test_answers_length(self):
        question_file = QuestionFile(test_file)
        self.assertEqual(len(question_file.get_answers()), 4)

if __name__ == '__main__':
    unittest.main()

我想导入两个类:QuestionQuestionFile,它们都位于:Testovnik\lib\question.pyTestovnik\lib\question_file.py

当我运行python question_tests.py时,它会抛出我:

C:\projects\python\Testovnik\tests>python question_tests.py
Traceback (most recent call last):
  File "question_tests.py", line 3, in <module>
    from Testovnik.lib.question import Question
ModuleNotFoundError: No module named 'Testovnik

我的问题是我应该采取什么样的方法让它发挥作用?

@Edit这是我的项目结构,所有文件(__init__.py文件都是空的):

enter image description here

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.getcwd()), r'Testovnik\lib')
from question import Question
from question_file import QuestionFile

#...#
相关问题