# python教程：模塊的搜索路徑

### 一、模塊搜索路徑的順序

• 先從內存中已經導入的模塊中尋找
• 內置的模塊
• 環境變量sys.path中找
``````import sys
print(f"sys.path: {sys.path}")

'''
['/Users/mac/Desktop/video/python/day16',
'/Users/mac/Desktop/video/python',
'/Applications/anaconda3/lib/python36.zip',
'/Applications/anaconda3/lib/python3.6',
'/Applications/anaconda3/lib/python3.6/site-packages',
'/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend']
'''
``````

#### 1 驗證先從內存中找

mmm.py

``````def f1():
print('from mmm.py f1')
``````

run.py

``````import time
import mmm

time.sleep(10)
import mmm
mmm.f1()  # from mmm.py f1
``````

#### 2 驗證先從內置中找

time.py

``````print('from time.py')
``````

run.py

``````import time
print(time)  # <module 'time' (built-in)>
``````

#### 3 驗證從sys.path中找

``````# run.py
import sys
sys.path.append(r'/Users/mac/Desktop/video/python')
print(sys.path)

import mmm
mmm.f1()
``````

### 二、搜索路徑以執行文件爲準

m1.py

``````#學習中遇到問題沒人解答？小編創建了一個Python學習交流羣：711312441
import sys
print('模塊m1中查看的結果',sys.path)
# import m2
from dir1 import m2
m2.f2()
``````

m2.py

``````import sys
print(sys.path)

def f2():
print('from f2')
``````

run.py

``````import sys
print('執行文件查看的結果：',sys.path)
from dir1 import m1
``````