Python17個常用內建模組總結 (運維)
<--目錄-->
1、getpass
2、os
3、sys
4、subprocess
5、hashlib
6、json
7、pickle
8、shutil
9、time
10、datetime
11、re
12、random
13、configparser
14、traceback
15、yaml
16、itertools
17、logging
1、getpass模組詳解
pwd = getpass.getpass("請輸入密碼:") #輸入密碼不可見
yh = getpass.getuser() #顯示當前登入系統使用者名稱;
2、os模組
os.getcwd() #獲取當前工作目錄,即當前python指令碼工作的目錄路徑
os.chdir("dirname") #改變當前指令碼工作目錄;相當於shell下cd
os.curdir #返回當前目錄: ('.')
os.pardir #獲取當前目錄的父目錄字串名:('..')
os.makedirs('dirname1/dirname2') #可生成多層遞迴目錄
os.removedirs('dirname1') #若目錄為空,則刪除,並遞迴到上一級目錄,如若也為空,則刪除,依此類推
os.mkdir('dirname') #生成單級目錄;相當於shell中mkdir dirname
os.rmdir('dirname') #刪除單級空目錄,若目錄不為空則無法刪除,報錯;相當於shell中rmdir dirname
os.listdir('dirname') #列出指定目錄下的所有檔案和子目錄,包括隱藏檔案,並以列表方式列印
os.remove() #刪除一個檔案
os.rename("oldname","newname") #重新命名檔案/目錄
os.stat('path/filename') #獲取檔案/目錄資訊
os.sep #輸出作業系統特定的路徑分隔符,win下為"\\",Linux下為"/"
os.linesep #輸出當前平臺使用的行終止符,win下為"\t\n",Linux下為"\n"
os.pathsep #輸出用於分割檔案路徑的字串
os.name #輸出字串指示當前使用平臺。win->'nt'; Linux->'posix'
os.system("bash command") #執行shell命令,直接顯示
os.environ #獲取系統環境變數
os.path.abspath(path) #返回path規範化的絕對路徑
os.path.split(path) #將path分割成目錄和檔名二元組返回
os.path.dirname(path) #返回path的目錄。其實就是os.path.split(path)的第一個元素
os.path.basename(path) #返回path最後的檔名。如何path以/或\結尾,那麼就會返回空值。即os.path.split(path)的第二個元素
os.path.exists(path) #如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) #如果path是絕對路徑,返回True
os.path.isfile(path) #如果path是一個存在的檔案,返回True。否則返回False
os.path.isdir(path) #如果path是一個存在的目錄,則返回True。否則返回False
os.path.join(path1[, path2[, ...]]) #將多個路徑組合後返回,第一個絕對路徑之前的引數將被忽略
os.path.getatime(path) #返回path所指向的檔案或者目錄的最後存取時間
os.path.getmtime(path) #返回path所指向的檔案或者目錄的最後修改時間
3、sys模組
sys.argv #命令列引數List,第一個元素是程式本身路徑
sys.exit(n) #退出程式,正常退出時exit(0)
sys.version #獲取Python解釋程式的版本資訊
sys.maxint #最大的Int值
sys.path #返回模組的搜尋路徑,初始化時使用PYTHONPATH環境變數的值
sys.platform #返回作業系統平臺名稱
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]
4、subprocess模組
執行系統命令
os.system
commands.* --廢棄,3.x中被移除
result = commands.getoutput('cmd')
以上執行shell命令的相關的模組和函式的功能均在 subprocess 模組中實現,並提供了更豐富的功能。
call
執行命令,返回狀態碼
ret = subprocess.call(["ls", "-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)
shell = True ,允許 shell 命令是字串形式
check_call
執行命令,如果執行狀態碼是 0 ,則返回0,否則拋異常
subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)
check_output(此下兩條命令在2.6執行失敗,要是2.7應該才可以)
執行命令,如果狀態碼是 0 ,則返回執行結果,否則拋異常
subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)
subprocess.Popen(...)
用於執行復雜的系統命令
引數:
args: #shell命令,可以是字串或者序列型別(如:list,元組)
bufsize: #指定緩衝。0 無緩衝,1 行緩衝,其他 緩衝區大小,負值 系統緩衝
stdin, stdout, stderr: #分別表示程式的標準輸入、輸出、錯誤控制代碼
preexec_fn: #只在Unix平臺下有效,用於指定一個可執行物件(callable object),它將在子程序執行之前被呼叫
close_sfs: #在windows平臺下,如果close_fds被設定為True,則新建立的子程序將不會繼承父程序的輸入、輸出、錯誤管道。所以不能將close_fds設定為True同時重定向子程序的標準輸入、輸出與錯誤(stdin, stdout, stderr)。
shell: #同上
cwd: #用於設定子程序的當前目錄
env: #用於指定子程序的環境變數。如果env = None,子程序的環境變數將從父程序中繼承。
universal_newlines: #不同系統的換行符不同,True -> 同意使用 \n
startupinfo與createionflags #只在windows下有效
將被傳遞給底層的CreateProcess()函式,用於設定子程序的一些屬性,如:主視窗的外觀,程序的優先順序等等
import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)
5、hashlib模組
用於加密相關的操作,代替了md5模組和sha模組,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 演算法
import hashlib
# ######## md5 ########
hash = hashlib.md5()
hash.update('admin')
print hash.hexdigest()
# ######## sha1 ########
hash = hashlib.sha1()
hash.update('admin')
print hash.hexdigest()
# ######## sha256 ########
hash = hashlib.sha256()
hash.update('admin')
print hash.hexdigest()
# ######## sha384 ########
hash = hashlib.sha384()
hash.update('admin')
print hash.hexdigest()
# ######## sha512 ########
hash = hashlib.sha512()
hash.update('admin')
print hash.hexdigest()
以上加密演算法雖然依然非常厲害,但時候存在缺陷,即:通過撞庫可以反解。所以,有必要對加密演算法中新增自定義key再來做加密。
import hashlib
# ######## md5 ########
hash = hashlib.md5('898oaFs09f')
hash.update('admin')
print hash.hexdigest()
還不夠吊?python 還有一個 hmac 模組,它內部對我們建立 key 和 內容 再進行處理然後再加密
import hmac
h = hmac.new('wueiqi')
h.update('hellowo')
print h.hexdigest()
6,7、json 和 pickle
用於序列化的兩個模組
json,用於字串 和 python資料型別間進行轉換
pickle,用於python特有的型別 和 python的資料型別間進行轉換
Json模組提供了四個功能:dumps、dump、loads、load
pickle模組提供了四個功能:dumps、dump、loads、load
pickle
>>> import pickle
>>> data = {'k1' : 123, 'k2' : 'hello'}
>>> p_str = pickle.dumps(data) #序列化
>>> print p_str
>>> loadsed = pickle.loads(p_str) #反序列化
>>> print loadsed
序列化到檔案
>>> li = ['wsyht',11,22,'ok','yes']
>>> pickle.dump(li,open('test.txt','w')) #序列化到檔案
>>> pickle.load(open('test.txt')) #從檔案反序列化出來
json
>>> import json
>>> data = {'k1':123,'k2':'abc'}
>>> str = json.dumps(data)
>>> stt= json.loads(str)
序列化到檔案
>>> li = ['wsyht',11,22,'ok','yes']
>>> json.dump(li,open('test.txt','w')) #序列化到檔案
>>> json.load(open('test.txt')) #從檔案反序化出來
8、shutil模組
shutil.make_archive(base_name, format,...)
建立壓縮包並返回檔案路徑,例如:zip、tar
base_name: 壓縮包的檔名,也可以是壓縮包的路徑。只是檔名時,則儲存至當前目錄,否則儲存至指定路徑,
如:www =>儲存至當前路徑
如:/Users/wupeiqi/www =>儲存至/Users/wupeiqi/
format:壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
root_dir:要壓縮的資料夾路徑(預設當前目錄)
owner:使用者,預設當前使用者
group:組,預設當前組
logger:用於記錄日誌,通常是logging.Logger物件
#將 /Users/wupeiqi/Downloads/test 下的檔案打包放置當前程式目錄
import shutil
ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
#將 /mnt下的檔案打包放置 /tmp目錄
import shutil
ret = shutil.make_archive("/tmp/www", 'gztar', root_dir='/mnt') #2.6用不了,2.7或許可以
類似於高階API,而且主要強大之處在於其對檔案的複製與刪除操作更是比較支援好。
相關API介紹
copyfile(src, dst)
從源src複製到dst中去。當然前提是目標地址是具備可寫許可權。丟擲的異常資訊為
IOException. 如果當前的dst已存在的話就會被覆蓋掉。
copyfile( src, dst) 從源src複製到dst中去。當然前提是目標地址是具備可寫許可權。丟擲的異常資訊為IOException. 如果當前的dst已存在的話就會被覆蓋掉
copymode( src, dst) 只是會複製其許可權其他的東西是不會被複制的
copystat( src, dst) 複製許可權、最後訪問時間、最後修改時間
copy( src, dst) 複製一個檔案到一個檔案或一個目錄
copy2( src, dst) 在copy上的基礎上再複製檔案最後訪問時間與修改時間也複製過來了,類似於cp –p的東西
copy2( src, dst) 如果兩個位置的檔案系統是一樣的話相當於是rename操作,只是改名;如果是不在相同的檔案系統的話就是做move操作
copytree(olddir,newdir,True/Flase) 把olddir拷貝一份newdir,如果第3個引數是True,則複製目錄時將保持資料夾下的符號連線,如果第3個引數是False,則將在複製的目錄下生成物理副本來替代符號連線
shutil.rmtree("te") 刪除一個目錄
import shutil
shutil.copyfile('f:/temp.txt', 'f:/os.txt') #複製檔案
shutil.copytree('f:/temp', 'f:/os') #複製目錄
# ######## zip的用法 ########
shutil 對壓縮包的處理是呼叫 ZipFile 和 TarFile 兩個模組來進行的,詳細:
import zipfile
# 壓縮
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log') #壓縮包寫入a.log
z.write('data.data') #寫入data檔案
z.close()
# 解壓
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
z.close()
9、time模組
三種表示主式:
1、時間戳 1970年1月1日後的秒
2、元組包含了:年、日、星期等...time.struct_time
3、格式化的字串 2014-11-11 11:11 print time.time()
#時間戳形式存在
print time.time()
print time.mktime(time.localtime()) #print (time.localtime())此為元組形式,這一整句意思是把元組形式轉化成時間戳形式
#元組形式存在
print time.gmtime() #可加時間戳引數
print time.localtime() #可加時間戳引數
print time.strptime('2014-11-11','%Y-%m-%d') #字串形式轉換成元組形式
#字串形式存在
print time.strftime('%Y-%m-%d') #預設當前時間,必須記住,工作中用得最多
print time.strftime('%Y-%m-%d',time.localtime()) #預設當前時間
print time.asctime()
print time.asctime(time.localtime())
print time.ctime(time.time())
時間的三種表示方式演示
>>> import time
>>> print time.time()
1469014348.5 #秒,時間戳的方式
>>> print time.gmtime()
time.struct_time(tm_year=2016, tm_mon=7, tm_mday=20, tm_hour=11, tm_min=25, tm_sec=53, tm_wday=2, tm_yday=202, tm_isdst=0)
>>> print time.strftime('%Y-%m-%d %H:%M:%S')
2016-07-20 19:36:16
10、datetime模組
import datetime
'''
datetime.date:表示日期的類。常用的屬性有year, month, day
datetime.time:表示時間的類。常用的屬性有hour, minute, second, microsecond
datetime.datetime:表示日期時間
datetime.timedelta:表示時間間隔,即兩個時間點之間的長度
timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
strftime("%Y-%m-%d")
'''
import datetime
print datetime.datetime.now()
print datetime.datetime.now() - datetime.timedelta(days=5)
11、re模組
compile
match search findall
group groups
正則表示式常用格式:
字元:\d \w \t .
次數:* + ? {m} {m,n}
示例:
#!#/usr/bin/env python
#coding:utf-8
import re
result1 = re.match('\d+', '1afsfweasfcxvsfd123') #在你給的字串起始位置去匹配,\d從數字開始找,+表示一個到多個
if result1: #當result1等於True的時候,就是匹配,如果匹配就輸出裡面的內容
print result1.group() #用group方法把他匹配的內容輸出出來
else:
print 'nothing'
result2 = re.search('\d+', 'alsfj3af') #在整個內容裡面去匹配,\d從數字開始找,+表示一個到多個
if result2:
print result2.group() #用group方法把他匹配的內容輸出出來
result3 = re.findall('\d+', 'asfaf11sf22lj33') #只要匹配全都拿出來
print result3
com = re.compile('\d+')
print com.findall('asfaf11sf22lj33')
result5 = re.search('(\d+)\w*(\d+)','aasflsjfa12aaljsf22lj13bb')
print result5.group() #所有匹配內容輸出
print result5.groups() #只把括號\d,也就是組裡面的內容輸出
result6 = re.search('a{3,5}','aaaaaa') #匹配3到5次的aaaaa輸出出來
print result6.group()
總結:
match:只在第一個字串開始找,如果沒有匹配,則不再繼續找,如果第一個字串中有,則只輸出第一個
searh: 在所有內容裡找,直到找到為止,但只輸出找到的第一個
findall:把所有找到的匹配的內容,都通過列表的形式打印出來
compile: 編譯之後再去匹配,這樣可以加快匹配的速度
group: 把他匹配的內容輸出出來
groups:分組
匹配的字元:
\d:表示數字的意思
\w: 代表下劃線,字母,數字
\t:製表符,除了回車以外的所有字元
匹配的次數:
* 大於等於0,0到多個
+ 大於等於1,1個到多個
? 0或1
{m} 次數,如a{6},出現6次a的進行匹配
{m,n} 如a{3,7} 出現3到7次的就進行匹配
例子1:
法1
>>> ip = '[email protected]#9436'
>>> import re
>>> re.findall('[0-9]{1,3}',ip)
['12', '23', '84', '23', '323', '4', '23', '192', '168', '32', '43', '342', '943', '6']
>>> re.findall('[0-9]{1,3}\.[0-9]{1,3}',ip)
['12.23', '192.168', '32.43']
>>> re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',ip)
['12.23.84', '192.168.32']
>>> re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',ip)
['192.168.32.43']
法2:
>>> re.findall('(\d+)',ip)
['12', '23', '84', '23', '3234', '23', '192', '168', '32', '43', '342', '9436']
>>> re.findall('(\.+\d+){1,3}',ip)
['.84', '.23', '.3234', '.43']
>>> re.findall('(?:\.+\d+){1,3}',ip) #?:表示匹配括號的那一組資料,必須連著
['.23.84', '.23', '.3234', '.168.32.43']
>>> re.findall('[0-9]{1,3}(?:\.+\d+){3}',ip)
['192.168.32.43']
法3:
>>> re.findall('(?:\d+\.+){3}\d{1,3}',ip)
['192.168.32.43']
法4:
>>> re.findall('(?:\d{1,3}\.){3}\d{1,3}',ip)
['192.168.32.43']
12、random模組
import random
print random.random()
print random.randint(1,2)
print random.randrange(1,10)
隨機驗證碼例項:
import random
checkcode = ''
for i in range(4):
current = random.randrange(0,4)
if current != i:
temp = chr(random.randint(65,90))
else:
temp = random.randint(0,9)
checkcode += str(temp)
print checkcode
13、ConfigParser模組
用於對特定的配置進行操作,當前模組的名稱在 python 3.x 版本中變更為 configparser。
1.讀取配置檔案
-read(filename) 直接讀取ini檔案內容
-sections() 得到所有的section,並以列表的形式返回
-options(section) 得到該section的所有option
-items(section) 得到該section的所有鍵值對
-get(section,option) 得到section中option的值,返回為string型別
-getint(section,option) 得到section中option的值,返回為int型別
2.寫入配置檔案
-add_section(section) 新增一個新的section
-set( section, option, value) 對section中的option進行設定
需要呼叫write將內容寫入配置檔案。
[[email protected] mnt]# cat data.txt
[sec_a]
a_key1 = 20
a_key2 = 10
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = $r
b_key4 = 127.0.0.1
>>> import ConfigParser
>>> cf = ConfigParser.ConfigParser()
>>> cf.read("data.txt")
['data.txt']
>>> secs = cf.sections() #獲得所有區域
>>> print 'sections:', secs
sections: ['sec_b', 'sec_a']
>>> opts = cf.options("sec_a")
>>> print 'options:', opts
options: ['a_key1', 'a_key2']
>>>
>>> for sn in secs:
... print cf.options(sn) #打印出每個區域的所有屬性
...
['b_key4', 'b_key1', 'b_key2', 'b_key3']
['a_key1', 'a_key2']
>>> str_val = cf.get("sec_a", "a_key1")
>>> int_val = cf.getint("sec_a", "a_key2")
>>> print "value for sec_a's a_key1:", str_val
value for sec_a's a_key1: 20
>>> print "value for sec_a's a_key2:", int_val
value for sec_a's a_key2: 10
>>> cf.set("sec_b", "b_key3", "new-$r")
>>> cf.set("sec_b", "b_newkey", "new-value")
>>> cf.add_section('a_new_section')
>>> cf.set('a_new_section', 'new_key', 'new_value')
>>> cf.write(open("data.txt", "w"))
>>> cf.has_section('a_new_section') #判斷存不存在[sec_a]
True
>>> cf.remove_section('sec_a') #刪除[sec_a]
True
>>> cf.has_section('a_section') #判斷存不存在[sec_a]
False
>>> cf.write(open("data.txt", "w"))
14、traceback模組
[[email protected] mnt]# cat test.py
#!/usr/bin/env python
#coding:utf-8
import traceback
try:
1/0
except Exception,e:
#print e
traceback.print_exc(file=open('tb.txt','w+'))
else:
print 'success'
15、yaml模組的使用
yaml在python上的具體實現:PyYaml
將yaml寫成配置指令碼test.yaml ,以下介紹如何讀寫yaml配置。
使用python的yaml庫PyYAML。http://pyyaml.org/
安裝到python lib下後就可以正常使用了。
#載入yaml
import yaml
f = open('test.yaml') #讀取檔案
x = yaml.load(f) #匯入
print x
f.close()
import yaml
f = open('d:/newtree.yaml', "w")
yaml.dump(dataMap, f)
f.close()
16、itertools模組的使用
[[email protected] mnt]# cat test.py
# ######## count(1) ########
import itertools
natuals = itertools.count(1) #count建立無限個迭代器
for n in natuals:
print n
# ######## cycle() ########
cycle()會把傳入的一個序列無限重複下去:
>>> import itertools
>>> cs = itertools.cycle('ABC') # 注意字串也是序列的一種
>>> for c in cs:
... print c
# ######## repeat() ########
repeat()負責把一個元素無限重複下去,不過如果提供第二個引數就可以限定重複次數:
>>> ns = itertools.repeat('A', 10)
>>> for n in ns:
... print n
...
列印10次'A'
# ######## takewhile() ########
>>> natuals = itertools.count(1)
>>> ns = itertools.takewhile(lambda x: x <= 10, natuals)
>>> for n in ns:
... print n
...
打印出1到10
# ######## chain() ########
for c in itertools.chain('ABC', 'XYZ'):
print c
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'
# ######## groupby() ########
groupby()把迭代器中相鄰的重複元素挑出來放在一起:
>>> for key, group in itertools.groupby('AAABBBCCAAA'):
... print key, list(group) # 為什麼這裡要用list()函式呢?
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
# ######## groupby() ########
實際上挑選規則是通過函式完成的,只要作用於函式的兩個元素返回的值相等,這兩個元素就被認為是在一組的,而函式返回值作為組的key。如果我們要忽略大小寫分組,就可以讓元素'A'和'a'都返回相同的key:
>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
... print key, list(group)
...
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']
# ######## imap() ########
>>> for x in itertools.imap(lambda x, y: x * y, [10, 20, 30], itertools.count(1)):
... print x
itertools
閱讀: 5044
Python的內建模組itertools提供了非常有用的用於操作迭代物件的函式。
首先,我們看看itertools提供的幾個“無限”迭代器:
>>> import itertools
>>> natuals = itertools.count(1)
>>> for n in natuals:
... print n
...
1
2
3
...
因為count()會建立一個無限的迭代器,所以上述程式碼會打印出自然數序列,根本停不下來,只能按Ctrl+C退出。
cycle()會把傳入的一個序列無限重複下去:
>>> import itertools
>>> cs = itertools.cycle('ABC') # 注意字串也是序列的一種
>>> for c in cs:
... print c
...
'A'
'B'
'C'
'A'
'B'
'C'
...
同樣停不下來。
repeat()負責把一個元素無限重複下去,不過如果提供第二個引數就可以限定重複次數:
>>> ns = itertools.repeat('A', 10)
>>> for n in ns:
... print n
...
列印10次'A'
無限序列只有在for迭代時才會無限地迭代下去,如果只是建立了一個迭代物件,它不會事先把無限個元素生成出來,事實上也不可能在記憶體中建立無限多個元素。
無限序列雖然可以無限迭代下去,但是通常我們會通過takewhile()等函式根據條件判斷來截取出一個有限的序列:
>>> natuals = itertools.count(1)
>>> ns = itertools.takewhile(lambda x: x <= 10, natuals)
>>> for n in ns:
... print n
...
打印出1到10
itertools提供的幾個迭代器操作函式更加有用:
chain()
chain()可以把一組迭代物件串聯起來,形成一個更大的迭代器:
for c in itertools.chain('ABC', 'XYZ'):
print c
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'
groupby()
groupby()把迭代器中相鄰的重複元素挑出來放在一起:
>>> for key, group in itertools.groupby('AAABBBCCAAA'):
... print key, list(group) # 為什麼這裡要用list()函式呢?
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
實際上挑選規則是通過函式完成的,只要作用於函式的兩個元素返回的值相等,這兩個元素就被認為是在一組的,而函式返回值作為組的key。如果我們要忽略大小寫分組,就可以讓元素'A'和'a'都返回相同的key:
>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
... print key, list(group)
...
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']
imap()
imap()和map()的區別在於,imap()可以作用於無窮序列,並且,如果兩個序列的長度不一致,以短的那個為準。
>>> for x in itertools.imap(lambda x, y: x * y, [10, 20, 30], itertools.count(1)):
... print x
注意imap()返回一個迭代物件,而map()返回list。當你呼叫map()時,已經計算完畢:
>>> r = map(lambda x: x*x, [1, 2, 3])
>>> r # r已經計算出來了
[1, 4, 9]
當你呼叫imap()時,並沒有進行任何計算:
>>> r = itertools.imap(lambda x: x*x, [1, 2, 3])
>>> r
<itertools.imap object at 0x103d3ff90>
# r只是一個迭代物件
itertools
閱讀: 5044
Python的內建模組itertools提供了非常有用的用於操作迭代物件的函式。
首先,我們看看itertools提供的幾個“無限”迭代器:
>>> import itertools
>>> natuals = itertools.count(1)
>>> for n in natuals:
... print n
...
1
2
3
...
因為count()會建立一個無限的迭代器,所以上述程式碼會打印出自然數序列,根本停不下來,只能按Ctrl+C退出。
cycle()會把傳入的一個序列無限重複下去:
>>> import itertools
>>> cs = itertools.cycle('ABC') # 注意字串也是序列的一種
>>> for c in cs:
... print c
...
'A'
'B'
'C'
'A'
'B'
'C'
...
同樣停不下來。
repeat()負責把一個元素無限重複下去,不過如果提供第二個引數就可以限定重複次數:
>>> ns = itertools.repeat('A', 10)
>>> for n in ns:
... print n
...
列印10次'A'
無限序列只有在for迭代時才會無限地迭代下去,如果只是建立了一個迭代物件,它不會事先把無限個元素生成出來,事實上也不可能在記憶體中建立無限多個元素。
無限序列雖然可以無限迭代下去,但是通常我們會通過takewhile()等函式根據條件判斷來截取出一個有限的序列:
>>> natuals = itertools.count(1)
>>> ns = itertools.takewhile(lambda x: x <= 10, natuals)
>>> for n in ns:
... print n
...
打印出1到10
itertools提供的幾個迭代器操作函式更加有用:
chain()
chain()可以把一組迭代物件串聯起來,形成一個更大的迭代器:
for c in itertools.chain('ABC', 'XYZ'):
print c
# 迭代效果:'A' 'B' 'C' 'X' 'Y' 'Z'
groupby()
groupby()把迭代器中相鄰的重複元素挑出來放在一起:
>>> for key, group in itertools.groupby('AAABBBCCAAA'):
... print key, list(group) # 為什麼這裡要用list()函式呢?
...
A ['A', 'A', 'A']
B ['B', 'B', 'B']
C ['C', 'C']
A ['A', 'A', 'A']
實際上挑選規則是通過函式完成的,只要作用於函式的兩個元素返回的值相等,這兩個元素就被認為是在一組的,而函式返回值作為組的key。如果我們要忽略大小寫分組,就可以讓元素'A'和'a'都返回相同的key:
>>> for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
... print key, list(group)
...
A ['A', 'a', 'a']
B ['B', 'B', 'b']
C ['c', 'C']
A ['A', 'A', 'a']
imap()
imap()和map()的區別在於,imap()可以作用於無窮序列,並且,如果兩個序列的長度不一致,以短的那個為準。
>>> for x in itertools.imap(lambda x, y: x * y, [10, 20, 30], itertools.count(1)):
... print x
...
10
40
90
注意imap()返回一個迭代物件,而map()返回list。當你呼叫map()時,已經計算完畢:
>>> r = map(lambda x: x*x, [1, 2, 3])
>>> r # r已經計算出來了
[1, 4, 9]
當你呼叫imap()時,並沒有進行任何計算:
>>> r = itertools.imap(lambda x: x*x, [1, 2, 3])
>>> r
<itertools.imap object at 0x103d3ff90>
# r只是一個迭代物件
必須用for迴圈對r進行迭代,才會在每次迴圈過程中計算出下一個元素:
>>> for x in r:
... print x
...
1
4
9
這說明imap()實現了“惰性計算”,也就是在需要獲得結果的時候才計算。類似imap()這樣能夠實現惰性計算的函式就可以處理無限序列:
>>> r = itertools.imap(lambda x: x*x, itertools.count(1))
>>> for n in itertools.takewhile(lambda x: x<100, r):
... print n
17、logging模組
用於便捷記錄日誌且執行緒安全的模組
import logging
logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=5)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')
對於等級:
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
出處:http://blog.51cto.com/yht1990/1845737
相關推薦
Python17個常用內建模組總結 (運維)
<--目錄-->1、getpass2、os3、sys4、subprocess5、hashlib6、json7、pickle8、shutil9、time10、datetime11、re12、random13、configparser14、traceback15、ya
常用內建模組
什麼是模組? 模組就是已經寫好,包含了python定義和宣告的檔案. 模組分為內建模組,第三方模組和自定義模組, 使用模組中的內容需要提前使用import匯入模組,使用方法為import 模組名 或者 from 模組名 import 函式名 使用第一種方法時,使用模組中的函式為模
python學習筆記:第21天 常用內建模組-1
目錄 一、collections模組 二、時間模組 也可以在我的個人部落格上閱讀 一、collections模組 1. Counter Counter是⼀個計數器,主要⽤統計字元的數量,之前如果我們要統計字串的話要寫如下演算法: s = 'Wed Nov 14 08:58:45 CS
Python4個內建資料結構(待補充)
分別是列表,元組,字典,集合 一、列表 有序的可變物件集合 列表中的每個元素從0開始編號。列表是動態的,因為它們可以根據需要擴充套件(收縮),不需要預宣告列表的大小 列表還是異構的,因為不需要預先宣告索要儲存物件的型別,完全可以在一個列表中混合不同型別的物件 列表是
Python常用內建模組——學習筆記
1、datetime:Python處理日期和時間的標準庫 引入方法: from datetime import datetime。 第一個datetime是模組,第二個datetime是類。 如果
hive---常用內建函式總結
數學函式:round(四捨五入):ceil(向上取整):floor(向下取整):上面的結果變為45字元函式:lower(轉小寫):upper(轉大寫):length(字串長度,字元數):concat(字串拼接):substr(求子串):substr(a,b):從字串a中,第b
day12-內建模組學習(三)
我的部落格呀,從以前的預習變成了複習了,複習的東西還沒有寫完,哎 今日目錄 1.序列化模組 2.加密模組 3.包的使用 4.random模組 5.shutil模組 開始今日份總結 1.序列化模組 在學習序列化模組之前,對於網路傳輸以及檔案寫入讀取都是採用將列表,字典這些資料型
Python基礎之十二常用內建模組
''' datetime datetime是Python處理日期和時間的標準庫 ''' ###########################獲取當前日期和時間 from datetime import datetime now =
python常用內建模組:datetime
使用 匯入datetime模組下的datetime類,如果只是import datetime 那麼呼叫要通過datetime.datetime 舉例:返回當前日期和時間: >>> from datetime import datetime
幾個內部排序演算法的總結(JAVA版)
插入排序 1、直接插入排序 public void insertSort(int[] a){ for(int i=0;i<a.length;i++){ int key=a[i]; int pos=i; while(pos>0&&a
常用原生JS方法總結(相容性寫法)
經常會用到原生JS來寫前端。。。但是原生JS的一些方法在適應各個瀏覽器的時候寫法有的也不怎麼一樣的。。。 今天下班有點累。。。 就來總結一下簡單的東西吧…… 備註:一下的方法都是包裹在一個EventUtil物件裡面的,直接採用物件字面量定義方法了。。。 ①新增事件方法 addHandle
ArcGIS內建地理轉換(適用中國)
最近又要做座標系轉換,本想把座標系的相關知識好好整理,寫一篇系統點的關於座標系的說明,但是時間總是不夠,因此先把工作中零碎用到的先記下來,以後有時間再整理吧。 座標系轉換包括投影座標系統轉換和地理座標系轉換,後者涉及到不同的橢球之間的轉換,又稱為地理變換。地理變換有三參、七
C++常用小技巧個人總結(持續更新)
求任意陣列長度 sizeof(array) / sizeof(array[0]), ※c++多關鍵字排序: struct node { int a;int b;int c;//三重引數 friend bool operator<(const node &am
web報表工具FineReport常用函式的用法總結(報表函式)
說明:本次總結中,凡是以tableName或viewName作為引數因子的。函式在呼叫的時候均按照先從私有資料來源中查詢,然後再從公有資料來源中查詢的順序。 CLASS CLASS(object):返回object物件的所屬的類。 CNMONEY CNMONEY(num
(轉)Awk使用案例總結(運維必會)
fig echo ... cat shell null 利用 for循環 3.1 以下知識點可能有不對之處,請參考最新Awk學習文章:http://lizhenliang.blog.51cto.com/7876557/1892112 原文:http://blog.51ct
隨想之二(運維)
運維 log 技術分享 blog clas web nbsp com center 一 運維的發展歷史 二 運維的管理 三 總體架構 四 基礎數據管理 五 運維自動化 隨想之二(運維)
Python學習(10)——常用的內建模組
跳過程序執行緒 跳過正則 1、datetime:處理日期和時間的標準庫 https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431937554888869fb52
Python 3 學習(二)—— 常用內建函式(網上收集整理)
文章目錄 輸入輸出 數學運算 型別轉換 序列操作 函式操作 Python 3 所有內建函式 輸入輸出 print(*objects, sep=' ', end='\n', file=sys.stdout,
JavaEE(1)——常用內建物件
1 實驗目的 掌握如何獲得請求引數; 瞭解如何通過請求物件獲得客戶資訊; 重點掌握request物件、session物件、application物件的用法; 重點掌握使用請求物件儲存資料和請求轉發。 2 實驗原理 2.1 request 物件 reques
Python3中的68個內建函式總結
一、內建函式 10大類 數學運算(7個) 型別轉換(24個) 序列操作(8個) 物件操作(9個) 反射操作(8個) 變數操作(2個) 互動操作(2個) 檔案操作(1個) 編譯執行(4個) 裝飾器(3個 1、數學運算(7個) (1)abs() 返