Python——常用模块
模塊,就是一堆實現了某個功能的代碼的集合。
一、time & datetime
time.time()
返回當前時間的時間戳,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。
1473344512.2949986time.sleep(秒數)
使用該方法可以讓程序休眠n秒,n可以是小數。
time.clock()
計算CPU執行時間。
time.gmtime()
結構化時間。Python time gmtime() 函數將一個時間戳轉換為UTC時區(0時區)的struct_time,可選的參數sec表示從1970-1-1以來的秒數。其默認值為 time.time(),函數返回time.struct_time類型的對象。(struct_time是在time模塊中定義的表示時間的對象)。
1 print(time.gmtime())輸出:
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=8, tm_hour=14, tm_min=37, tm_sec=16, tm_wday=3, tm_yday=252, tm_isdst=0)# 年 月 日 小時 分鐘 秒 本周第4天(0表示周日) 本年第252天
time.localtime()
?將一個時間戳轉換為當前時區的struct_time。secs參數未提供,則以當前時間為準。
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=8, tm_hour=22, tm_min=44, tm_sec=25, tm_wday=3, tm_yday=252, tm_isdst=0) 1 import time 2 3 4 # print(time.clock()) #返回處理器時間,3.3開始已廢棄 , 改成了time.process_time()測量處理器運算時間,不包括sleep時間,不穩定,mac上測不出來 5 # print(time.altzone) #返回與utc時間的時間差,以秒計算\ 6 # print(time.asctime()) #返回時間格式"Fri Aug 19 11:14:16 2016", 7 # print(time.localtime()) #返回本地時間 的struct time對象格式 8 # print(time.gmtime(time.time()-800000)) #返回utc時間的struc時間對象格式 9 10 # print(time.asctime(time.localtime())) #返回時間格式"Fri Aug 19 11:14:16 2016", 11 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上 12 13 14 15 # 日期字符串 轉成 時間戳 16 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #將 日期字符串 轉成 struct時間對象格式 17 # print(string_2_struct) 18 # # 19 # struct_2_stamp = time.mktime(string_2_struct) #將struct時間對象轉成時間戳 20 # print(struct_2_stamp) 21 22 23 24 #將時間戳轉為字符串格式 25 # print(time.gmtime(time.time()-86640)) #將utc時間戳轉換成struct_time格式 26 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #將utc struct_time格式轉成指定的字符串格式 27 28 29 30 31 32 #時間加減 33 import datetime 34 35 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925 36 #print(datetime.date.fromtimestamp(time.time()) ) # 時間戳直接轉成日期格式 2016-08-19 37 # print(datetime.datetime.now() ) 38 # print(datetime.datetime.now() + datetime.timedelta(3)) #當前時間+3天 39 # print(datetime.datetime.now() + datetime.timedelta(-3)) #當前時間-3天 40 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #當前時間+3小時 41 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #當前時間+30分 42 43 44 # 45 # c_time = datetime.datetime.now() 46 # print(c_time.replace(minute=3,hour=2)) #時間替換 更多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)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所指向的文件或者目錄的最后修改時間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]hashlib
用于加密相關的操作,3.x里代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。
import hashlibm = 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. """passdef 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 還有一個 hmac 模塊,它內部對我們創建 key 和 內容 再進行處理然后再加密
散列消息鑒別碼,簡稱HMAC,是一種基于消息鑒別碼MAC(Message Authentication Code)的鑒別機制。使用HMAC時,消息通訊的雙方,通過驗證消息中加入的鑒別密鑰K來鑒別消息的真偽;
一般用于網絡通信中消息加密,前提是雙方先要約定好key,就像接頭暗號一樣,然后消息發送把用key把消息加密,接收方用key + 消息明文再加密,拿加密后的值 跟 發送者的相對比是否相等,這樣就能驗證消息的真實性,及發送者的合法性了。
import hmac h = hmac.new(b'天王蓋地虎', b'寶塔鎮河妖') print h.hexdigest()https://www.tbs-certificates.co.uk/FAQ/en/sha256.html
paramiko
http://www.cnblogs.com/franknihao/p/6536255.html
pip3 install paramiko?1 用戶名密碼--執行命令
import paramikossh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('127.0.0.1', 22, 'oliver', '123456') stdin, stdout, stderr = ssh.exec_command('df -h') print stdout.read() ssh.close();?2 秘鑰--執行命令
import paramikoprivate_key_path = '/home/auto/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(private_key_path)ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('127.0.0.1 ', 22, 'oliver', key)stdin, stdout, stderr = ssh.exec_command('df -h') print stdout.read() ssh.close()?3 ?用戶名密碼--上傳下載
import os,sys import paramikot = paramiko.Transport(('192.168.1.46',22)) t.connect(username='oliver',password='123456') sftp = paramiko.SFTPClient.from_transport(t) sftp.put('/tmp/test.py','/tmp/test.py') t.close()import os,sys import paramikot = paramiko.Transport(('192.168.1.46',22)) sftp = paramiko.SFTPClient.from_transport(t) sftp.get('/tmp/test.py','/tmp/test2.py') t.close()?4 ?秘鑰--上傳下載
import paramikopravie_key_path = '/home/auto/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(pravie_key_path)t = paramiko.Transport(('192.168.1.46',22)) t.connect(username='oliver',pkey=key)sftp = paramiko.SFTPClient.from_transport(t) sftp.put('/tmp/test3.py','/tmp/test3.py') t.close()import paramikopravie_key_path = '/home/auto/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(pravie_key_path)t = paramiko.Transport(('192.168.1.46',22)) t.connect(username='oliver',pkey=key)sftp = paramiko.SFTPClient.from_transport(t) sftp.get('/tmp/test3.py','/tmp/test4.py') t.close()subprocess
#執行命令,返回命令執行狀態 , 0 or 非0 >>> retcode = subprocess.call(["ls", "-l"])#執行命令,如果命令結果為0,就正常返回,否則拋異常 >>> subprocess.check_call(["ls", "-l"]) 0#接收字符串格式命令,返回元組形式,第1個元素是執行狀態,第2個是命令結果 >>> subprocess.getstatusoutput('ls /bin/ls') (0, '/bin/ls')#接收字符串格式命令,并返回結果 >>> subprocess.getoutput('ls /bin/ls') '/bin/ls'#執行命令,并返回結果,注意是返回結果,不是打印,下例結果返回給res >>> res=subprocess.check_output(['ls','-l']) >>> res b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'#上面那些方法,底層都是封裝的subprocess.Popen poll() Check if child process has terminated. Returns returncodewait() Wait for child process to terminate. Returns returncode attribute.terminate() 殺掉所啟動進程 communicate() 等待任務結束stdin 標準輸入stdout 標準輸出stderr 標準錯誤pid The process ID of the child process.#例子 >>> 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' >>> subprocess.run(["ls", "-l"]) # doesn't capture output CompletedProcess(args=['ls', '-l'], returncode=0)>>> subprocess.run("exit 1", shell=True, check=True) Traceback (most recent call last):... subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE) CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0, stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')調用subprocess.run(...)是推薦的常用方法,在大多數情況下能滿足需求,但如果你可能需要進行一些復雜的與系統的交互的話,你還可以用subprocess.Popen(),語法如下:
p = subprocess.Popen("find / -size +1000000 -exec ls -shl {} \;",shell=True,stdout=subprocess.PIPE) print(p.stdout.read())可用參數:
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()函數,用于設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等
終端輸入的命令分為兩種:
輸入即可得到輸出,如:ifconfig
輸入進行某環境,依賴再輸入,如:python
需要交互的命令示例:
import subprocessobj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) obj.stdin.write('print 1 \n ') obj.stdin.write('print 2 \n ') obj.stdin.write('print 3 \n ') obj.stdin.write('print 4 \n ')out_error_list = obj.communicate(timeout=10) print out_error_listsubprocess實現sudo 自動輸入密碼:
import subprocessdef mypass():mypass = '123' #or get the password from anywherereturn mypassecho = subprocess.Popen(['echo',mypass()],stdout=subprocess.PIPE,)sudo = subprocess.Popen(['sudo','-S','iptables','-L'],stdin=echo.stdout,stdout=subprocess.PIPE,)end_of_pipe = sudo.stdoutprint "Password ok \n Iptables Chains %s" % end_of_pipe.read()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'}最常用的匹配語法:
e.match 從頭開始匹配 re.search 匹配包含 re.findall 把所有匹配到的字符放到以列表中的元素返回 re.splitall 以匹配到的字符當做列表分隔符 re.sub 匹配字符并替換
反斜杠的困擾
與大多數編程語言相同,正則表達式里使用"\"作為轉義字符,這就可能造成反斜杠困擾。假如你需要匹配文本中的字符"\",那么使用編程語言表示的正則表達式里將需要4個反斜杠"\\\\":前兩個和后兩個分別用于在編程語言里轉義成反斜杠,轉換成兩個反斜杠后再在正則表達式里轉義成一個反斜杠。Python里的原生字符串很好地解決了這個問題,這個例子中的正則表達式可以使用r"\\"表示。同樣,匹配一個數字的"\\d"可以寫成r"\d"。有了原生字符串,你再也不用擔心是不是漏寫了反斜杠,寫出來的表達式也更直觀。
僅需輕輕知道的幾個匹配模式:
re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同) M(MULTILINE): 多行模式,改變'^'和'$'的行為(參見上圖) S(DOTALL): 點任意匹配模式,改變'.'的行為?ConfigParser
http://www.open-open.com/lib/view/open1398169869203.html
Python中有ConfigParser類,可以很方便的從配置文件中讀取和寫入數據(如DB的配置,路徑的配置)。
常見的配置文件格式ini文件,其他格式還有conf文件。ini文件示例:
[School] ip = 10.15.40.123 mask = 255.255.255.0 gateway = 10.15.40.1 dns = 211.82.96.1[Match] ip = 172.17.29.120 mask = 255.255.255.0 gateway = 172.17.29.1 dns = 0.0.0.0?配置文件的寫入和讀取:
import configparserconfig = configparser.ConfigParser() config.read("IpConfig.ini") # 如果文件不存在,則自動創建# 在School節下面添加參數 try:config.add_section("School") # 注意:如果文件中已經存在相應的項目,則不能再增加同名的節。config.set("School","IP","10.15.40.123")config.set("School","Mask","255.255.255.0")config.set("School","Gateway","10.15.40.1")config.set("School","DNS","211.82.96.1") except configparser.DuplicateSectionError:print("Section 'School' already exists")#由于ini文件中可能有同名項,所以做了異常處理 try:config.add_section("Match")config.set("Match","IP","172.17.29.120")config.set("Match","Mask","255.255.255.0")config.set("Match","Gateway","172.17.29.1")config.set("Match","DNS","0.0.0.0") except configparser.DuplicateSectionError:print("Section 'Match' already exists")# 添加完參數后,要寫入文件 config.write(open("IpConfig.ini", "w"))ip=config.get("School","IP") mask=config.get("School","mask") gateway=config.get("School","Gateway") dns=config.get("School","DNS")print((ip,mask+"\n"+gateway,dns))?生成的文件:
自己封裝一個類,調用時更方便:
# encoding:utf-8 # name:mod_config.pyimport configparser import osclass Config(object):def __init__(self, filename):self.config = configparser.ConfigParser()self.path = os.path.split(os.path.realpath(__file__))[0] + '/' + filename# 其中 os.path.split(os.path.realpath(__file__))[0] 得到的是當前文件模塊的目錄self.config.read(self.path)# 設置config配置文件def setConfig(self, section, option, value):# 由于ini文件中可能有同名項,所以做了異常處理try:self.config.add_section(section)except configparser.DuplicateSectionError:print("Section '%s' already exists" % section)self.config.set(section, option, value)def writeConfig(self):# 添加完參數后,要寫入文件return self.config.write(open(self.path, "w"))# 獲取config配置文件def getConfig(self, section, key):return self.config.get(section, key)if __name__ == '__main__':# import pdb;pdb.set_trace()conf_obj = Config("IpConfig.ini")conf_obj.setConfig("DB", "host", "127.0.0.1")conf_obj.setConfig("School", "description", "")gw = conf_obj.getConfig("School", "gateway")mask = conf_obj.getConfig("Match", "mask")print gw, maskyaml
http://blog.csdn.net/Marksinoberg/article/details/52979419
csv
http://www.cnblogs.com/liujinhong/p/5937527.html
argparse、docopt、click
?https://python.freelycode.com/contribution/detail/643
prettytable
?http://www.cnblogs.com/xiao1/p/5878680.html
http://blog.csdn.net/bellwhl/article/details/9066493
colorama
?命令行著色工具。
collections
略
matplotlib
https://www.ibm.com/developerworks/cn/linux/l-matplotlib/
?
numpy
?
sklearn
?
FileDialog
?
tkinter
?
scipy
?
opencv-python
?
?
?
?
轉載于:https://www.cnblogs.com/pyramid1001/p/5854809.html
總結
以上是生活随笔為你收集整理的Python——常用模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JVM堆内存控制/分代垃圾回收
- 下一篇: 编程基础python学习2完结