'How to import modules from site-packages when in a different directory?
I made a module and moved it to /root/Downloads/Python-3.5.2/Lib/site-packages.
When I run bash command python3 in this folder to start the ide and import the module it works. However if I run python3 in any other directory (e.g. /root/Documents/Python) it says
ImportError: No module named 'exampleModule'
I was under the impression that Python would automatically search for modules in site-packages regardless of the directory. How can I fix it so that it will work regardless of where I am?
Solution 1:[1]
There is two ways to make python find your module:
- add the path where you module reside in your
PYTHONPATHas suggested by bmat - add the path where you module reside in your script like this:
import sys sys.path.insert(0, '/root/Downloads/Python-3.5.2/Lib/site-packages')
Solution 2:[2]
Instead of moving the module I would suggest you add the location of the module to the PYTHONPATH environment variable. If this is set then the python interpreter will know where to look for your module.
e.g. on Linux
export PYTHONPATH=$PYTHONPATH:<insert module location here>
Solution 3:[3]
If you are a window user and you are getting import issues from site-packages then you can add the path of your site-packages to env variable
C:\Users\hp\AppData\Local\Programs\Python\Python310\Lib\site-packages (site-package directory)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | bmat |
| Solution 3 | akash maurya |

