电竞比分网-中国电竞赛事及体育赛事平台

分享

學Python的初體驗——模塊簡述

 千鋒Python學堂 2019-12-10

Python的模塊有很多很多,就像紛亂繁雜的API,都分別歸屬于這些模塊,假如我們明白了哪個模塊干什么事,能干什么,能做到什么,或者說 —— 理論上作為大眾應用如此廣泛的它應該能做到什么,那即使我們不知道API,Google或百度的時候也有方向,有一個精準的搜索關鍵詞,這對于我們解決問題的效率來講,至關重要。

Python的模塊,你可以理解成就是一個個的js文件,或者說處理不同領域事情的util工具類。比如用于操作系統(tǒng)相關的os,用于系統(tǒng)指令相關的sys,用于發(fā)送請求的requests,用于線程管理的thread和threading,用于數(shù)學計算,隨機數(shù)處理,字符串匹配的math、random和re,用于時間相關操作的time、datetime和calendar,用于連接MySQL數(shù)據(jù)庫的pymysql(不同數(shù)據(jù)庫有不同的包),用于處理json相關的json…有很多很多,還有類似于node stream那樣的管道操作流操作的包,用于消息隊列的包(比如處理kafka相關的東西)等等第三方包,數(shù)不盡,用不竭,其實也正因為有這樣的生態(tài),它才能茁壯長大。(回想當初,連一個高低電平的變換都要自己來實現(xiàn),想想都是淚。。。不過方便的同時,也把我們都變成了一個個的API調用者= =,好吧,扯遠了、、、)

我們一個個看:

1、os模塊 —— 文件操作系統(tǒng):

os,經(jīng)常裝系統(tǒng)的人可能經(jīng)常會說,os鏡像,xxxx.os文件等等,其實os的意思是Operating System,也就是操作系統(tǒng),既然是操作系統(tǒng),操作文件,那應該跟node的fs差不多吧,不管怎樣,來看一下。
既然是操作系統(tǒng)和文件,那應該會有新建,修改,文件路徑,打開,關閉,讀取文件等等的基本操作,也會有文件權限,文件重命名等等的操作,就像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('當前絕對路徑為:' + os.path.abspath('./'))
path = os.path.abspath('./')

if not os.path.exists(path + '/hello'): # 判斷路徑是否存在
os.mkdir(path + '/hello') # 建路徑

# 類似JavaScript中的try catch,異常捕獲
try:
# 建文件,這種方式是默認的建文件方式,如txt是gbk的編碼格式,若需要儲存成另外編碼格式的,可以通過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)建并寫入文件時報錯:' + str(error))

print('當前工作目錄為:' + 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,這里就會在結果list里面返回,[程序名,argv0,1,2,...]

# print(sys.modules) # 當前引入的模塊信息
print(sys.platform) # 操作平臺信息
print(sys.version) # python版本信息
print(sys.copyright) # python的版權信息

# print(sys.getswitchinterval()) # 線程切換間隔
# print(sys.thread_info) # 當前線程信息

# print(sys.stdin) # 輸入相關
# print(sys.stdout) # 輸出相關
# print(sys.stderr) # 錯誤相關
# ...

3、requests模塊 —— http通訊:

既然requests是發(fā)http請求,處理通訊,按照我們的一般對于http或者更廣泛點的Tcp的理解,既然是請求,那就有get、post、put跟delete,實際上也是這樣的,requests.get,requests.post,requests.put,requests.delete,當然,還有一個綜合性的將get、post等等類型當做參數(shù)傳進去的requests.request。而且,注意,這是后臺,后臺,后臺!重要的事情說3遍,你不用再去管跨域,不存在跨域。。。記得有一次在閑聊的時候聊到前端接口調不通,我跟他提了跨域,然后有一次他后臺調不通了,他也以為是跨域,我用nginx,他也搞了一個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

# 此外它還有,不常用的,可暫不理會
# requests.head
# requests.patch

print(getData())
print(requestData())

4、thread和threading模塊 —— 線程管理:

python通過thread跟threading來管理線程,先導入模塊

import _thread # thread與threading有沖突,python3在原有的基礎上增加了一個_私有前綴,不影響使用
import threading # threading更高級,也可以代替舊的thread,我們日常用threading就可以啦。

看看它是怎么用的:

def test_threading (self):

# 開多條線程

def run():
print('當前執(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模塊 —— 日歷、時間:

看到上面的線程管理代碼時,里面我們很熟悉的sleep函數(shù)就來自于time模塊。獲取時間,這里就沒什么需要說的了,不過它本身附帶的格式化是比較好用的了,無需像JavaScript那樣去getFullYear()或去單獨實現(xiàn)格式化。

def test_time(self):

print(time.time()) # 時間戳
print(time.localtime()) # 當?shù)貢r間
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 當?shù)貢r間,格式化成帶星期幾格式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 當?shù)貢r間,并做格式化成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')

簡單看看輸出:

學Python的初體驗——模塊簡述

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 —— 解析

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多