Python的模塊有很多很多,就像紛亂繁雜的API,都分別歸屬于這些模塊,假如我們明白了哪個(gè)模塊干什么事,能干什么,能做到什么,或者說 —— 理論上作為大眾應(yīng)用如此廣泛的它應(yīng)該能做到什么,那即使我們不知道API,Google或百度的時(shí)候也有方向,有一個(gè)精準(zhǔn)的搜索關(guān)鍵詞,這對(duì)于我們解決問題的效率來講,至關(guān)重要。 Python的模塊,你可以理解成就是一個(gè)個(gè)的js文件,或者說處理不同領(lǐng)域事情的util工具類。比如用于操作系統(tǒng)相關(guān)的os,用于系統(tǒng)指令相關(guān)的sys,用于發(fā)送請(qǐng)求的requests,用于線程管理的thread和threading,用于數(shù)學(xué)計(jì)算,隨機(jī)數(shù)處理,字符串匹配的math、random和re,用于時(shí)間相關(guān)操作的time、datetime和calendar,用于連接MySQL數(shù)據(jù)庫的pymysql(不同數(shù)據(jù)庫有不同的包),用于處理json相關(guān)的json…有很多很多,還有類似于node stream那樣的管道操作流操作的包,用于消息隊(duì)列的包(比如處理kafka相關(guān)的東西)等等第三方包,數(shù)不盡,用不竭,其實(shí)也正因?yàn)橛羞@樣的生態(tài),它才能茁壯長(zhǎng)大。(回想當(dāng)初,連一個(gè)高低電平的變換都要自己來實(shí)現(xiàn),想想都是淚。。。不過方便的同時(shí),也把我們都變成了一個(gè)個(gè)的API調(diào)用者= =,好吧,扯遠(yuǎn)了、、、) 我們一個(gè)個(gè)看: 1、os模塊 —— 文件操作系統(tǒng): os,經(jīng)常裝系統(tǒng)的人可能經(jīng)常會(huì)說,os鏡像,xxxx.os文件等等,其實(shí)os的意思是Operating System,也就是操作系統(tǒng),既然是操作系統(tǒng),操作文件,那應(yīng)該跟node的fs差不多吧,不管怎樣,來看一下。 既然是操作系統(tǒng)和文件,那應(yīng)該會(huì)有新建,修改,文件路徑,打開,關(guān)閉,讀取文件等等的基本操作,也會(huì)有文件權(quán)限,文件重命名等等的操作,就像node中的fs.read、fs.close、fs.path…,而Python中的os模塊,這些操作也是有的,它也是os.close,os.read,os.mkdir,os.open,os.rename等等。。。是不是發(fā)現(xiàn)也特別像JavaScript? def test_os(self): print('os_start') print('當(dāng)前絕對(duì)路徑為:' + os.path.abspath('./')) path = os.path.abspath('./')
if not os.path.exists(path + '/hello'): # 判斷路徑是否存在 os.mkdir(path + '/hello') # 建路徑 # 類似JavaScript中的try catch,異常捕獲 try: # 建文件,這種方式是默認(rèn)的建文件方式,如txt是gbk的編碼格式,若需要儲(chǔ)存成另外編碼格式的,可以通過codecs模塊來創(chuàng)建文件 # f = open(path + '/hello/test.txt', 'w')
f = codecs.open(path + '/hello/test.txt', 'w', 'utf-8') # 建文件 f.write('hello world, 你好啊, \n') f.close()
except Exception as error: print('創(chuàng)建并寫入文件時(shí)報(bào)錯(cuò):' + str(error))
print('當(dāng)前工作目錄為:' + os.getcwd())
# 文件重命名 —— rename / renames os.rename(path + '/hello/test.txt', path + '/hello/hello.txt') # 將之前的test.txt文件重命名為hello.txt文件
print('os_end')
2、sys模塊 —— 系統(tǒng)指令與信息: 直接貼吧,主要是讀取信息 def test_sys(self):
print(sys.argv) # 獲取命令行的參數(shù),就比如我們剛剛執(zhí)行了python ./package.py,這里就會(huì)在結(jié)果list里面返回,[程序名,argv0,1,2,...] # print(sys.modules) # 當(dāng)前引入的模塊信息 print(sys.platform) # 操作平臺(tái)信息 print(sys.version) # python版本信息 print(sys.copyright) # python的版權(quán)信息
# print(sys.getswitchinterval()) # 線程切換間隔 # print(sys.thread_info) # 當(dāng)前線程信息
# print(sys.stdin) # 輸入相關(guān) # print(sys.stdout) # 輸出相關(guān) # print(sys.stderr) # 錯(cuò)誤相關(guān) # ...
3、requests模塊 —— http通訊: 既然requests是發(fā)http請(qǐng)求,處理通訊,按照我們的一般對(duì)于http或者更廣泛點(diǎn)的Tcp的理解,既然是請(qǐng)求,那就有g(shù)et、post、put跟delete,實(shí)際上也是這樣的,requests.get,requests.post,requests.put,requests.delete,當(dāng)然,還有一個(gè)綜合性的將get、post等等類型當(dāng)做參數(shù)傳進(jìn)去的requests.request。而且,注意,這是后臺(tái),后臺(tái),后臺(tái)!重要的事情說3遍,你不用再去管跨域,不存在跨域。。。記得有一次在閑聊的時(shí)候聊到前端接口調(diào)不通,我跟他提了跨域,然后有一次他后臺(tái)調(diào)不通了,他也以為是跨域,我用nginx,他也搞了一個(gè)nginx… def test_requests(self):
def getData(): resp = requests.get('https://www.imooc.com/article/getarticlelist?marking=fe&page=4') return resp.content
def requestData(): resp = requests.request('GET', 'https://www.imooc.com/article/getarticlelist?marking=fe&page=4') return resp.content # requests.get # requests.post # requests.put # requests.delete # requests.request
# 此外它還有,不常用的,可暫不理會(huì) # requests.head # requests.patch
print(getData()) print(requestData())
4、thread和threading模塊 —— 線程管理: python通過thread跟threading來管理線程,先導(dǎo)入模塊 import _thread # thread與threading有沖突,python3在原有的基礎(chǔ)上增加了一個(gè)_私有前綴,不影響使用 import threading # threading更高級(jí),也可以代替舊的thread,我們?nèi)粘S胻hreading就可以啦。
看看它是怎么用的: def test_threading (self):
# 開多條線程
def run(): print('當(dāng)前執(zhí)行的線程為:' + str(threading.current_thread())) time.sleep(2)
thread_list = [] i = 5 while i > 0: t = threading.Thread(target=run) thread_list.append(t) i -= 1 for t in thread_list: t.start()
5、time、datetime和calendar模塊 —— 日歷、時(shí)間: 看到上面的線程管理代碼時(shí),里面我們很熟悉的sleep函數(shù)就來自于time模塊。獲取時(shí)間,這里就沒什么需要說的了,不過它本身附帶的格式化是比較好用的了,無需像JavaScript那樣去getFullYear()或去單獨(dú)實(shí)現(xiàn)格式化。 def test_time(self):
print(time.time()) # 時(shí)間戳 print(time.localtime()) # 當(dāng)?shù)貢r(shí)間 print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 當(dāng)?shù)貢r(shí)間,格式化成帶星期幾格式 print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 當(dāng)?shù)貢r(shí)間,并做格式化成2019-11-27 20:00:00
print(datetime.date.today()) # 年月日 print(datetime.date(2019, 11, 27)) # 年月日
print(calendar.month(2019, 11)) # 生成日歷頁 print(calendar.isleap(2020)) # 判斷傳入的年份是否為閏年 print(calendar.month(2019, 11, w=3, l=2)) # 修改日歷行列間距,這里是3字符和2字符 print('\ntime和datetime')
簡(jiǎn)單看看輸出: 
6、json模塊 —— 處理json: def test_json(self):
obj = { 'a': 1, 'b': 2 } objStr = json.dumps(obj) # JavaScript里的JSON.stringify —— 序列化 print(objStr) print(json.loads(objStr)) # JavaScript里的JSON.parse —— 解析
|