adding directory to sys.path /PYTHONPATH
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island
--
Chapters
00:00 Adding Directory To Sys.Path /Pythonpath
00:36 Accepted Answer Score 298
01:16 Answer 2 Score 18
01:26 Answer 3 Score 2
01:40 Answer 4 Score 13
02:05 Thank you
--
Full question
https://stackoverflow.com/questions/1611...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #mechanize #pythonimport #pythonpath
#avk47
ACCEPTED ANSWER
Score 298
This is working as documented.  Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths.  sys.path.append() appends to the existing path.  See here and here.  If you want a particular directory to come first, simply insert it at the head of sys.path:
import sys
sys.path.insert(0,'/path/to/mod_directory')
That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly.  See, for example, the answers to this question.
ANSWER 2
Score 18
You could use:
import os
path = 'the path you want'
os.environ['PATH'] += ':'+path
ANSWER 3
Score 13
As to me, i need to caffe to my python path. I can add it's path to the file
/home/xy/.bashrc by add
export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH
to my /home/xy/.bashrc file.
But when I use pycharm, the path is still not in.
So I can add path to PYTHONPATH variable, by run -> edit Configuration.
ANSWER 4
Score 2
When running a Python script from Powershell under Windows, this should work:
$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"
# Now run the actual script
python your_script.py
