1

In my workspace , the directory structure is like this:

F:
  `-- src
     |-- lib
     |   `-- base.py
     `-- tests
         `-- test_modulexx
             `-- test_module_001.py

In the file test_module_001.py , I import the lib module.

test_module_001.py:

import os
from lib.base import BaseTestCase

Sometimes when I run it in the folder F:\src. it raise a error:

File "F:\src\tests\test_modulexx\test_module_001.py", line 2, in <module>
    from lib.base import BaseTestCase
ModuleNotFoundError: No module named 'lib'

If you have met the same error and you have solved it, Can you share it to me ? And also, I want to know why it doesn't work. Let's end the problem thoroughly.

2 Answers2

0

I hava tried to debug this and found something maybe helpful to it.

when I start python console . and import the module lib ,it works.then I check the sys.path, the result is like this.

>> import lib
>> import sys
>> sys.path
['', 'C:\\Python\\Anaconda3\\python37.zip', 'C:\\Python\\Anaconda3\\DLLs', 'C:\\Python\\Anaconda3\\lib', 'C:\\Python\\Anaconda3', 'C:\\Python\\Anaconda3\\lib\\site-packages', '', 'C:\\Python\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Python\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Python\\Anaconda3\\lib\\site-packages\\Pythonwin']

the first element in the list is ''. then I set breakpoint in the python file before it import the module lib.

file test_module_001.py:

import pdb;pdb.set_trace()
import lib

then I execute python tests\test_modulexx\test_module_001.py in the windows console and print sys.path

>f:\src\tests\test_modulexx\test_module_001.py(2)<module>()
->import lib
(Pdb)import sys
(Pdb)sys.path
['F:\\src\\tests\\test_modulexx', 'C:\\Python\\Anaconda3\\python37.zip', 'C:\\Python\\Anaconda3\\DLLs', 'C:\\Python\\Anaconda3\\lib', 'C:\\Python\\Anaconda3', 'C:\\Python\\Anaconda3\\lib\\site-packages', 'C:\\Python\\Anaconda3\\lib\\site-packages\\win32', 'C:\\Python\\Anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Python\\Anaconda3\\lib\\site-packages\\Pythonwin']
(Pdb)import lib
*** ModuleNotFoundError: No module named 'lib'

the first element in sys.path has been changed. now it is F:\\src\\tests\\test_modulexx. I add '' to sys.path and import lib. it works.

(Pdb)sys.path.append('')
(Pdb)import lib
(Pdb)

I think the reason is that Scope of Python importing module is defined in the sys.path. and the '' means the current path.

-1

Check that you have added the required __init__.py files for your modules. See: Working with Modules in Python