gpt4 book ai didi

python-3.6 - Python3.6错误: ModuleNotFoundError: No module named 'src'

转载 作者:行者123 更新时间:2023-12-03 09:35:16 28 4
gpt4 key购买 nike

我知道以前有人问过类似的问题......但我有一个很快的疑问......
我一直在关注这个链接:https://www.python-course.eu/python3_packages.php
我的代码结构:

my-project
-- __init__.py
-- src
-- __init__.py
-- file1.py
-- test
-- __init__.py
-- test_file1.py
test_file1.py:
import unittest
from src.file1 import *

class TestWriteDataBRToOS(unittest.TestCase):
def test_getData(self):
sampleData = classInFile1()
sampleData.getData()
self.assertNotEqual(sampleData.usrname, "")

if __name__ == '__main__':
unittest.main()
在这里我得到错误:
ModuleNotFoundError: No module named 'src'
如果我更改为:
import sys
sys.path.insert(0, '../src')
import unittest
from file1 import *
那么它的工作原理!
谁能帮我理解为什么它不像上面粘贴的链接中描述的那样工作,或者任何替代方式而不是写 sys.path.insert(0, '../src')陈述。
谢谢!
编辑:
从我的项目目录执行后: python -m unittest test/test_file1/TestWriteDataBRToOS我收到如下更新的错误。
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/lib/python2.7/unittest/__main__.py", line 12, in <module>
main(module=None)
File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__
self.parseArgs(argv)
File "/usr/lib/python2.7/unittest/main.py", line 149, in parseArgs
self.createTests()
File "/usr/lib/python2.7/unittest/main.py", line 158, in createTests
self.module)
File "/usr/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
suites = [self.loadTestsFromName(name, module) for name in names]
File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
module = __import__('.'.join(parts_copy))
ImportError: Import by filename is not supported.

最佳答案

您必须从 my-project 运行测试文件夹,而不是来自 test文件夹。

python -m unittest test.test_file1.TestWriteDataBRToOS

关于python-3.6 - Python3.6错误: ModuleNotFoundError: No module named 'src' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51049663/

28 4 0