我尝试/home/myname/bin
通过将以下内容插入到我的目录中来添加到我的 PYTHONPATH 中.bashrc
:
if [ -d ~/bin ]; then
export PYTHONPATH=$PYTHONPATH:/home/myname/bin
fi
不幸的是,这似乎将我的主目录添加到了 Python 的搜索路径中,如在 Python 中运行以下命令所示:
>>> import sys
>>> sys.path
['', '/home/myname', '/home/myname/bin', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
请注意,echo $PYTHONPATH
只是返回:/home/myname/bin
。
答案1
问题在于您包含了 的现有值PYTHONPATH
。但是,该变量未设置,因此其计算结果为空字符串。出于某种原因,这似乎包括了python
您的$HOME
目录。据推测,这是默认目录:
$ python -c 'import sys; print sys.path'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk2']
但是,如果我设置PYTHONPATH
为空字符串,则$HOME
包含 my:
$ PYTHONPATH=""; python -c 'import sys; print sys.path'
['', '/home/terdon', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk2']
PYTHONPATH
因此,当您在设置时包含当前值时,您将获得以下行为:
$ PYTHONPATH="$PYTHONPATH:$HOME/bin" python -c 'import sys; print sys.path'
['', '/home/terdon', '/home/terdon/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk2']
正确的设置方法是仅提供您想要添加的目录:
$ PYTHONPATH="$HOME/bin" python -c 'import sys; print sys.path'
['', '/home/terdon/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk2']
或者,为了安全起见,万一定义了它,请检查它是否为空并采取相应措施:
if [ -d ~/bin ]; then
[ -z "$PYTHONPATH" ] &&
export PYTHONPATH="/home/myname/bin" ||
export PYTHONPATH="$PYTHONPATH:/home/myname/bin"
fi