Python – sys.path

測試環境為 CentOS 8 x86_64 (虛擬機)

sys.path 是 python 可搜尋模組的路徑,其儲存資料格式為 list , 其中的 path[0] 為程式所在的路徑.

參考文章 – https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/374849/

  • 範例 : 使用 PYTHONPATH 環境變數
    [root@localhost ~]# env PYTHONPATH='/root/ben' python3
    Python 3.6.8 (default, Mar 25 2022, 11:15:52) 
    [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.path
    ['', '/root/ben', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages']
    >>> 
    
  • 範例 : 使用 .pth 檔案
    透過建立 .pth 檔案新增可搜尋模組的路徑

    [root@localhost ~]# vi ben.pth
    /rrot/ben
    

    這 .pth 檔案要放在哪裡? 透過 site.getusersitepackages 來檢視.

    >>> import site
    >>> site.getusersitepackages()
    '/root/.local/lib/python3.6/site-packages'
    
    [root@localhost ~]# mkdir -p /root/.local/lib/python3.6/site-packages/
    [root@localhost ~]# cp ben.pth /root/.local/lib/python3.6/site-packages/
    

    重新進入 python 命令列就可以看到新增了 /root/ben 路徑.

    [root@localhost ~]# python3
    Python 3.6.8 (default, Mar 25 2022, 11:15:52) 
    [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.path
    ['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/root/.local/lib/python3.6/site-packages', '/root/ben', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages']
    
  • 範例 : 透過 sys.path.append
    >>> sys.path.append('/root/ben1')
    >>> sys.path
    ['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/root/.local/lib/python3.6/site-packages', '/root/ben', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages', '/root/ben1']
    

    不過重新進入需再次使用 sys.path.append 讓路徑新增.

    >>> 
    [8]+  已停止               python3
    [root@localhost ~]# python3
    Python 3.6.8 (default, Mar 25 2022, 11:15:52) 
    [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.path
    ['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/root/.local/lib/python3.6/site-packages', '/root/ben', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages']
    
沒有解決問題,試試搜尋本站其他內容

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料