1. 程式人生 > >python匯入自帶模組和自定義模組

python匯入自帶模組和自定義模組

模組就是已經開發好的程式碼功能,自己直接匯入進來,直接使用。
匯入分為python 或selenium 自帶的模組和自己寫的自定義模組,下面根據這兩個方向寫一下分別匯入的方法。

1.匯入自帶模組
import sys #匯入sys模組,呼叫此模組時的方法 print sys.argv
from sys import argv #匯入sys模組下的argv 方法,呼叫此模組時的方法 print argv
import multiprocessing as multi #針對名字比較長的模組 可以用as起一個別名
from sys import * #匯入sys 模組下的所有方法,呼叫此模組下額某一個方法不用加sys.~ ,例:print argv .這種呼叫方法不建議使用,防止自帶和自創的變數或方法名字混淆。

2.匯入自寫模組
2.1 被呼叫檔案和當前需要呼叫的檔案在同一目錄下
folder
----test_a.py
----test_b.py
----start.py
在start.py 下引入test_a.py的方法:
import test_a 或 from test_a import *

2.2 被呼叫檔案和當前需要呼叫的檔案在不同目錄下,且為子目錄
folder
----test_a.py
----test_b.py

start.py
在start.py 下引入test_a.py的方法:
先把folder 由普通資料夾改成包package  ,新建一個__init__.py 的空檔案
  folder
----_init_.py
----test_a.py
----test_b.py

start.py
然後引入import folder.test_a 或 from folder.test_a import *

2.3 被呼叫檔案和當前需要呼叫的檔案在不同資料夾目錄
folder_a
----test_a.py
----test_b.py

folder_b
----start.py

在start.py 下引入test_a.py的方法:
先把folder 由普通資料夾改成包package  ,新建一個__init__.py 的空檔案
 folder_a
----_init_.py
----test_a.py
----test_b.py

folder_b
----start.py

然後引入import folder_a.test_a 或 from folder_a.test_a import *

參考資料:https://www.cnblogs.com/Sumomo0516/p/6010575.html