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

2024-04-18 12:36:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的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


Tags: 文件项目frompytestimportselflib
1条回答
网友
1楼 · 发布于 2024-04-18 12:36:32

你可以试试这个:

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

#...#

相关问题 更多 >