sys.path用法介绍

介绍

sys.path指定模块搜索路径的列表。默认情况下,python导入文件或者模块,会在sys.path里找模块的路径。如果在当前搜索路径列表sys.path中找不到该模块的话,就会报错。

用法

最常用的用法就是向sys.path中添加搜索路径

import sys
sys.path.append(path)  # path 代表的是一个路径

举例

  • 查看当前搜索路径

    import sys
    print(sys.path)
    
    ['/home/nsy/nlp/exp3', 
    '/home/nsy/anaconda3/envs/nlp/lib/python36.zip', 
    '/home/nsy/anaconda3/envs/nlp/lib/python3.6', 
    '/home/nsy/anaconda3/envs/nlp/lib/python3.6/lib-dynload',
    '/home/nsy/anaconda3/envs/nlp/lib/python3.6/site-packages',
    '/home/nsy/anaconda3/envs/nlp/lib/python3.6/site-packages/keras_contrib-2.0.8-py3.6.egg',
    '/home/nsy/anaconda3/envs/nlp/lib/python3.6/site-packages/dl_segmenter-0.1_SNAPSHOT-py3.6.egg']
    
    • 也就是说,如果我要导入python模块,那么会在这些路径下寻找
  • 添加新的路径

    • 我现在有一个模块new_package,路径为/home/nsy/nlp/new_package,我直接import new_package是会报错的,因为在上面那些路径中找不到

      import sys
      import new_package
      
      >>Traceback (most recent call last):
        File "sys_test.py", line 2, in <module>
          import new_package
      ModuleNotFoundError: No module named 'new_package'
      
    • 添加路径,成功运行

      import sys
      sys.path.append('/home/nsy/nlp')
      import new_package
      print(sys.path)
      
      ['/home/nsy/nlp/exp3',
       '/home/nsy/anaconda3/envs/nlp/lib/python36.zip',
       '/home/nsy/anaconda3/envs/nlp/lib/python3.6',
       '/home/nsy/anaconda3/envs/nlp/lib/python3.6/lib-dynload',
       '/home/nsy/anaconda3/envs/nlp/lib/python3.6/site-packages',
       '/home/nsy/anaconda3/envs/nlp/lib/python3.6/site-packages/keras_contrib-2.0.8-py3.6.egg',
       '/home/nsy/anaconda3/envs/nlp/lib/python3.6/site-packages/dl_segmenter-0.1_SNAPSHOT-py3.6.egg',
       '/home/nsy/nlp']
      

你可能感兴趣的:(Python,python,开发语言)