1. 程式人生 > >【Python】sys.path.append動態新增搜尋路徑設定

【Python】sys.path.append動態新增搜尋路徑設定

如何將路徑“永久"新增到sys.path?

sys.path是Python的搜尋模組的路徑集,是一個list

可以在python 環境下使用sys.path.append(path)新增相關的路徑,但在退出python環境後自己新增的路徑就會自動消失了!

可以使用以下命令輸入當前python 的搜尋路徑:

python -c"import sys;print '當前的python是:'+sys.prefix;print '\n'.join(sys.path)"

練習使用sys.path.append方法新增路徑,顯示退出python會消失!

python -c"import sys;print '當前的python是:'+sys.prefix;sys.path.append(r'E:\DjangoWord' ) ;print '\n'.join(sys.path)"

再次執行,會發現 自己新增路徑E:\DjangoWord()不存在了!

python -c"import sys;print '當前的python是:'+sys.prefix;print '\n'.join(sys.path)"

為解決這個問題,可以有以下方法:

將自己做的py檔案放到 site_packages 目錄下:

下面命令顯示了 site-packages 目錄:

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib() "

 但是這樣做會導致一個問題,即各類模組都放到此資料夾的話,會導致亂的問題,這一點是顯而易見的。

 注意,也不建立子資料夾,再將自己的模組放到子資料夾解決問題,這會導致使用import 語句時錯誤。

使用pth檔案,在 site-packages 檔案中建立 .pth檔案,將模組的路徑寫進去,一行一個路徑,以下是一個示例,pth檔案也可以使用註釋:

# .pth file for the  my project(這行是註釋)

E:\DjangoWord

E:\DjangoWord\mysite

E:\DjangoWord\mysite\polls

這個不失為一個好的方法,但存在管理上的問題,而且不能在不同的python版本中共享。

使用PYTHONPATH環境變數,在這個環境變數中輸入相關的路徑,不同的路徑之間用逗號(英文的!)分開,如果PYTHONPATH 變數還不存在,可以建立它!

路徑會自動加入到sys.path中,而且可以在不同的python版本中共享,應該是一樣較為方便的方法。

關於與python相關的環境變數有那些,請參考:

以下是該環境變數的描述:

PYTHONPATH?

Augment the default search path for module files. The format is the same as the shell’s PATH : one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.

In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.

The default search path is installation dependent, but generally begins with prefix /lib/python version (see PYTHONHOME above). It is always appended to PYTHONPATH .

An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options . The search path can be manipulated from within a Python program as the variable sys.path .