简体   繁体   中英

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 (eg /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?

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.

eg on Linux

export PYTHONPATH=$PYTHONPATH:<insert module location here>

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.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.

eg on Linux

export PYTHONPATH=$PYTHONPATH:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM