本文翻译自: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. 然后,您将能够从脚本中查看这些路径内的所有模块。