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?
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .
The easiest way to change it is to add a file /usr/local/lib/python2. 6/dist-packages/site-packages. pth containing ../site-packages . Alternatively, maybe you can teach the package to use site.
In order to import a module, the directory having that module must be present on PYTHONPATH. It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys. path, so will add the parent directory path to the sys.
There is two ways to make python find your module:
PYTHONPATH
as suggested by bmatimport sys
sys.path.insert(0, '/root/Downloads/Python-3.5.2/Lib/site-packages')
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With