模塊,用一砣代碼實現了某個功能的代碼集合。html
相似於函數式編程和麪向過程編程,函數式編程則完成一個功能,其餘代碼用來調用便可,提供了代碼的重用性和代碼間的耦合。而對於一個複雜的功能來,可能須要多個函數才能完成(函數又能夠在不一樣的.py文件中),n個 .py 文件組成的代碼集合就稱爲模塊。node
如:os 是系統相關的模塊;file是文件操做相關的模塊python
模塊分爲三種:git
開源模塊shell
1、下載安裝編程
下載安裝有兩種方式:數據結構
1.app
yum
pip
apt-get
2.dom
下載源碼
解壓源碼
進入目錄
編譯源碼 python setup.py build
安裝源碼 python setup.py install
注:在使用源碼安裝時,須要使用到gcc編譯和python開發環境,因此,須要先執行:函數式編程
yum install gcc
yum install python
-
devel
或
apt
-
get python
-
dev
import time print(time.altzone)#返回與utc時間的時間差,以秒計算 print(time.asctime())#返回時間格式 print(time.localtime())#返回本地時間的時間對象 print(time.asctime(time.localtime())) t2 = time.strptime("2016-11-11 23:30","%Y-%m-%d %H:%M")#將日期字符串轉換struct時間對象格式 t2_stamp = time.mktime(t2)#將struct時間對象轉成時間戳 print(t2_stamp) t3 = time.localtime(t2_stamp) #stamp to time struct t3_str = time.strftime("%Y_%m_%d.log", t3)#將utc struct_time格式轉成指定的字符串格式 print(t3_str) import time import datetime print(datetime.datetime.now()) print(datetime.date.fromtimestamp(time.time()))#時間戳轉成日期格式 print(datetime.datetime.now()+datetime.timedelta(3))#時間加3天 print(datetime.datetime.now()+datetime.timedelta(hours=3))#時間加3小時 now = datetime.datetime.now() print(now.timetuple())#時間對象
random模塊
import random import string print(random.random()) print(random.randint(0,5))#0-5之間隨機產生 print(random.randrange(0,5))#0-4之間隨機產生 str_source = string.ascii_letters + string.digits print(''.join(random.sample(str_source,5)))#隨機生成5位a-zA-Z0-9
生成隨機驗證碼
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)
shutil
高級的 文件、文件夾、壓縮包 處理模塊
import shutil f1 = open("random mod.py") f2 = open("random_new.py","w") shutil.copyfileobj(f1,f2) shutil.copy(r"C:\Users\Administrator\PycharmProjects\py_s15\day3\筆記","test")#拷貝文件和權限 shutil.copy2()#拷貝文件和狀態信息 shutil.copyfile() shutil.copytree(r"C:\Users\Administrator\PycharmProjects\py_s15\day3","day3_new")#遞歸去拷貝文件 shutil.make_archive(r"c:\day3",format="zip",root_dir=r"C:\Users\Administrator\PycharmProjects\py_s15\day3")#建立壓縮包並返回文件路勁 #對壓縮包的處理調用zipfile和tarfile處理 import zipfile zip_obj = zipfile.ZipFile(r"c:\zip_test.zip","w") zip_obj.write("test") zip_obj.write(r"C:\Users\Administrator\PycharmProjects\py_s15\day3")#把test和C:\Users\Administrator\PycharmProjects\py_s15\day3壓縮到c:\zip_test.zip zip_obj.close() import tarfile EXCLUDE_FILES = ['字典', '筆記', 'lyrics'] def exclude_function(tarinfo): if tarinfo.name in EXCLUDE_FILES and tarinfo.isdir(): print("filter...") return None else: return tarinfo tar = tarfile.open(r'c:\your.tar','w') tar.add(r"C:\Users\Administrator\PycharmProjects\py_s15\day3",filter=exclude_function,arcname="alex") tar.add(r"c:\zip_test.zip") tar.close()
shelve模塊
shelve模塊是一個簡單的k,v將內存數據經過文件持久化的模塊,能夠持久化任何pickle可支持的python數據格式
import shelve d = shelve.open('shelve_test') def stu_data(name,age): print('register stu',name,age) name = ['alex','rain','test'] info = {'name':'alex','age':22} d['test'] = name d['info'] = info d['func'] = stu_data
xml處理模塊
xml的格式以下,就是經過<>節點來區別數據結構的:
<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data>
xml協議在各個語言裏的都 是支持的,在python中能夠用如下模塊操做xml
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() print(root.tag) #遍歷xml文檔 for child in root: print(child.tag, child.attrib) for i in child: print(i.tag,i.text) #只遍歷year 節點 for node in root.iter('year'): print(node.tag,node.text)
用於生成和修改常見配置文檔,當前模塊的名稱在 python 3.x 版本中變動爲 configparser。
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} topsecret = config['topsecret.server.com'] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('example.ini', 'w') as configfile: config.write(configfile)
hashlib模塊
import hashlib m = hashlib.md5() m.update(b"Hello") m.update(b"It's me") print(m.digest()) m.update(b"It's been a long time since last time we ...") print(m.digest()) #2進制格式hash print(len(m.hexdigest())) #16進制格式hash ''' def digest(self, *args, **kwargs): # real signature unknown """ Return the digest value as a string of binary data. """ pass def hexdigest(self, *args, **kwargs): # real signature unknown """ Return the digest value as a string of hexadecimal digits. """ pass ''' 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())
不少程序都有記錄日誌的需求,而且日誌中包含的信息即有正常的程序訪問日誌,還可能有錯誤、警告等信息輸出,python的logging模塊提供了標準的日誌接口,你能夠經過它存儲各類格式的日誌,logging的日誌能夠分爲 debug()
, info()
, warning()
, error()
and critical() 5個級別,
下面咱們看一下怎麼用。
import logging logging.warning("user [alex] attempted wrong password more than 3 times") logging.critical("server is down") #輸出 WARNING:root:user [alex] attempted wrong password more than 3 times CRITICAL:root:server is down
日誌寫到文件中
import logging logging.basicConfig(filename='example.log',level=logging.INFO) logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too')
其中下面這句中的level=loggin.INFO意思是,把日誌紀錄級別設置爲INFO,也就是說,只有比日誌是INFO或比INFO級別更高的日誌纔會被紀錄到文件裏
日誌格式
%(name)s |
Logger的名字 |
%(levelno)s |
數字形式的日誌級別 |
%(levelname)s |
文本形式的日誌級別 |
%(pathname)s |
調用日誌輸出函數的模塊的完整路徑名,可能沒有 |
%(filename)s |
調用日誌輸出函數的模塊的文件名 |
%(module)s |
調用日誌輸出函數的模塊名 |
%(funcName)s |
調用日誌輸出函數的函數名 |
%(lineno)d |
調用日誌輸出函數的語句所在的代碼行 |
%(created)f |
當前時間,用UNIX標準的表示時間的浮 點數表示 |
%(relativeCreated)d |
輸出日誌信息時的,自Logger建立以 來的毫秒數 |
%(asctime)s |
字符串形式的當前時間。默認格式是 「2003-07-08 16:49:45,896」。逗號後面的是毫秒 |
%(thread)d |
線程ID。可能沒有 |
%(threadName)s |
線程名。可能沒有 |
%(process)d |
進程ID。可能沒有 |
%(message)s |
用戶輸出的消息 |
若是想同時把log打印在屏幕和文件日誌裏
import logging #create logger logger = logging.getLogger('TEST-LOG') logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create file handler and set level to warning fh = logging.FileHandler("access.log") fh.setLevel(logging.WARNING) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) # add ch and fh to logger logger.addHandler(ch) logger.addHandler(fh) # 'application' code logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')
文件自動截斷
import logging from logging import handlers logger = logging.getLogger(__name__) log_file = "timelog.log" #fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3) fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3) formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) logger.warning("test1") logger.warning("test12") logger.warning("test13") logger.warning("test14")
re模塊
經常使用正則表達式符號
'.' 默認匹配除\n以外的任意一個字符,若指定flag DOTALL,則匹配任意字符,包括換行 '^' 匹配字符開頭,若指定flags MULTILINE,這種也能夠匹配上(r"^a","\nabc\neee",flags=re.MULTILINE) '$' 匹配字符結尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也能夠 '*' 匹配*號前的字符0次或屢次,re.findall("ab*","cabb3abcbbac") 結果爲['abb', 'ab', 'a'] '+' 匹配前一個字符1次或屢次,re.findall("ab+","ab+cd+abb+bba") 結果['ab', 'abb'] '?' 匹配前一個字符1次或0次 '{m}' 匹配前一個字符m次 '{n,m}' 匹配前一個字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 結果'abb', 'ab', 'abb'] '|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 結果'ABC' '(...)' 分組匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 結果 abcabca456c '\A' 只從字符開頭匹配,re.search("\Aabc","alexabc") 是匹配不到的 '\Z' 匹配字符結尾,同$ '\d' 匹配數字0-9 '\D' 匹配非數字 '\w' 匹配[A-Za-z0-9] '\W' 匹配非[A-Za-z0-9] 's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 結果 '\t' '(?P<name>...)' 分組匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 結果{'province': '3714', 'city': '81', 'birthday': '1993'}
經常使用匹配語法
re.match 從頭開始匹配
re.search 匹配包含
re.findall 把全部匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符當作列表分隔符
re.sub 匹配字符並替換
subprocess模塊
os.system輸出命令結果到屏幕,返回命令執行狀態
os.popen('dir').read()會保存命令的執行結果輸出
經常使用方法
1.subprocess.run(['df -h'],shell = True)
2.#接收字符串格式命令,返回元組形式,第1個元素是執行狀態,第2個是命令結果
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
stdin 標準輸入
stdout 標準輸出
stderr 標準錯誤
3.>>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
>>> p.stdout.read()
b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /\n'
parser = optparse.OptionParser() parser.add_option("-s","--server", dest="server", help="ftp server ip_addr") parser.add_option("-P","--port",type="int", dest="port", help="ftp server port") parser.add_option("-u","--username", dest="username", help="username") parser.add_option("-p","--password", dest="password", help="password") self.options , self.args = parser.parse_args()