本文翻譯自:Permanently add a directory to PYTHONPATH?
Whenever I use
sys.path.append
, the new directory will be added.
每當我使用sys.path.append
,都會添加新目錄。 However, once I close python, the list will revert to the previous (default?) values.
但是,一旦我關閉python,清單将恢複為以前的值(預設值)。How do I permanently add a directory to
PYTHONPATH
?
如何将目錄永久添加到PYTHONPATH
? #1樓
參考:https://stackoom.com/question/EH3g/将目錄永久添加到PYTHONPATH
#2樓
Instead of manipulating
PYTHONPATH
you can also create a path configuration file .
除了操縱PYTHONPATH
您還可以建立路徑配置檔案 。 First find out in which directory Python searches for this information:
首先找出Python在哪個目錄中搜尋此資訊:python -m site --user-site
For some reason this doesn't seem to work in Python 2.7.
由于某些原因,這似乎在Python 2.7中不起作用。There you can use:
在那裡您可以使用:python -c 'import site; site._script()' --user-site
Then create a
.pth
file in that directory containing the path you want to add (create the directory if it doesn't exist).
然後在該目錄中建立一個.pth
檔案,其中包含要添加的路徑(如果該目錄不存在,則建立該目錄)。 For example:
例如:# find directory
SITEDIR=$(python -m site --user-site)
# create if it doesn't exist
mkdir -p "$SITEDIR"
# create new .pth file with our path
echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"
#3樓
In case anyone is still confused - if you are on a Mac, do the following:
如果仍然有人困惑-如果您使用的是Mac,請執行以下操作:- Open up Terminal 打開終端
- Type
輸入open .bash_profile
open .bash_profile
- In the text file that pops up, add this line at the end:
在彈出的文本檔案中,在末尾添加以下行:export PYTHONPATH=$PYTHONPATH:foo/bar
export PYTHONPATH=$PYTHONPATH:foo/bar
- Save the file, restart the Terminal, and you're done 儲存檔案,重新啟動終端,然後完成
#4樓
On linux you can create a symbolic link from your package to a directory of the PYTHONPATH without having to deal with the environment variables.
在Linux上,您可以建立從軟體包到PYTHONPATH目錄的符号連結,而不必處理環境變量。Something like:
就像是:ln -s /your/path /usr/lib/pymodules/python2.7/
#5樓
For me it worked when I changed the
.bash_profile
file.
對我來說,當我更改.bash_profile
檔案時,它起作用了。 Just changing
.bashrc
file worked only till I restarted the shell.
僅更改.bashrc
檔案才有效,直到重新啟動外殼程式為止。 For python 2.7 it should look like:
對于python 2.7,它應如下所示:export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"
at the end of the
.bash_profile
file.
在.bash_profile
檔案的末尾。 #6樓
This works on Windows
這适用于Windows- On Windows, with Python 2.7 go to the Python setup folder. 在Windows上,對于Python 2.7,請轉到Python設定檔案夾。
- Open Lib/site-packages. 打開庫/站點包。
- Add an example.pth empty file to this folder. 将example.pth空檔案添加到此檔案夾。
- Add the required path to the file, one per each line. 将所需的路徑添加到檔案,每行一個。
Then you'll be able to see all modules within those paths from your scripts.
然後,您将能夠從腳本中檢視這些路徑内的所有子產品。