为什么我自己的库不能导入到我的项目中?
Why can't my own library be imported in my project?
我有一个简单的 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()
我想导入两个 类:Question
和 QuestionFile
,它们都相应地位于:Testovnik\lib\question.py
和 Testovnik\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
文件为空):
你可以试试这个:
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
#...#
我有一个简单的 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()
我想导入两个 类:Question
和 QuestionFile
,它们都相应地位于:Testovnik\lib\question.py
和 Testovnik\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
文件为空):
你可以试试这个:
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
#...#