Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 319
J. Doe Avatar asked Sep 29 '16 12:09

J. Doe


People also ask

How can I import modules if file is not in same directory?

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.

How do I import a module from one directory to another?

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 .

How do I change the path of a Python site package?

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.

How do I import a module from the root directory?

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.


2 Answers

There is two ways to make python find your module:

  1. add the path where you module reside in your PYTHONPATH as suggested by bmat
  2. 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')
    
like image 156
dtrckd Avatar answered Sep 27 '22 17:09

dtrckd


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>
like image 20
bmat Avatar answered Sep 27 '22 16:09

bmat