J. Doe
J. Doe

Reputation: 101

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?

Upvotes: 10

Views: 20465

Answers (3)

akash maurya
akash maurya

Reputation: 656

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

enter image description here

C:\Users\hp\AppData\Local\Programs\Python\Python310\Lib\site-packages (site-package directory)

Upvotes: 0

dtrckd
dtrckd

Reputation: 662

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')
    

Upvotes: 4

bmat
bmat

Reputation: 304

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>

Upvotes: 5

Related Questions