others-how to solve ModuleNotFoundError no module found error in python ?

1. Purpose

In this post, I will show you how to solve ModuleNotFoundError: No module named error in python, just as follows:

When I trying to start a python problem, I got the following error:

(test_env) ➜  test_chatserver git:(master) ✗ python ui/zzz_test/test_vectorstore_query.py 
Traceback (most recent call last):
  File "/Users/bswen/PycharmProjects/test_vectorstore_query.py", line 11, in <module>
    from server.knowledge_base.kb_service.base import EmbeddingsFunAdapter
ModuleNotFoundError: No module named 'server'



2. Solution

You can solve this problem by following these steps:

We should check our environment variable PYTHONPATH, because PYTHONPATH is the Python search path. By default, the modules we import will be searched from PYTHONPATH.

1) First, check PYTHONPATH environment variable

(test_env) ➜  test_chatserver git:(master) ✗ python -c 'import sys; print(sys.path)' 
['', '/Users/bswen/miniconda3/envs/test_env/lib/python310.zip', '/Users/bswen/miniconda3/envs/test_env/lib/python3.10', '/Users/bswen/miniconda3/envs/test_env/lib/python3.10/lib-dynload', '/Users/bswen/miniconda3/envs/test_env/lib/python3.10/site-packages']

2) Then, add current directory to PYTHONPATH

(test_env) ➜  test_chatserver git:(master)export PYTHONPATH=.                                                                                        
(test_env) ➜  test_chatserver git:(master) ✗ python -c 'import sys; print(sys.path)' 
['', '/Users/bswen/PycharmProjects/LangchainProjects/test_brain/test_chatserver', '/Users/bswen/miniconda3/envs/test_env/lib/python310.zip', '/Users/bswen/miniconda3/envs/test_env/lib/python3.10', '/Users/bswen/miniconda3/envs/test_env/lib/python3.10/lib-dynload', '/Users/bswen/miniconda3/envs/test_env/lib/python3.10/site-packages']

Now run the app again, it works!



3. How to set PYTHONPATH

1) Method 1: Add path in command window

export PYTHONPATH=$PYTHONPATH:/home/bswen

Note: This method only takes effect in the current command window, that is, if you open a new Terminal window and navigate to the current directory, the path you just added will not be printed in PYTHONPATH.

2) Method 2: Add in python code:

import sys sys.path.append('/home/bswen/')

4. Summary

In this post, I demonstrated how to solve the module not found error in python, the keypoint is to check and change your PYTHONPATH. That’s it, thanks for your reading.