我嘗試/home/myname/bin
透過將以下內容插入我的.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