Python—模块
模塊?引用某大大的話就是“模塊,用一坨代碼實現了某個功能的代碼集合。”
類似于函數式編程和面向過程編程,函數式編程則完成一個功能,其他代碼用來調用即可,提供了代碼的重用性和代碼間的耦合。而對于一個復雜的功能來,可能需要多個函數才能完成(函數又可以在不同的.py文件中),n個 .py 文件組成的代碼集合就稱為模塊。 例如:os是系統相關的模塊,time是時間相關的模塊。 模塊分為三種: ·自定義模塊; ·內置標準模塊(又稱標準庫); ·開源模塊。1、自定義模塊: 1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By Sandler 4 5 DATABASE = { 6 "engine":"mysql", 7 "host":"localhost", 8 "port":3306, 9 "user":"root", 10 "passwd":"123" 11 } 2、開源模塊: 開源模塊安裝有兩種方式: 1 下載源碼 2 解壓源碼 3 進入目錄 4 編譯源碼 python setup.py build 5 安裝源碼 python setup.py install
現在一般都不需要編譯了,直接安裝源碼就可以,但,在使用源碼安裝時,需要使用到gcc和python開發環境,所以,需要先執行:
1 yum install gcc 2 yum install python-devel 3 apt-get python-dev #apt-get是ubuntu系統上安裝程序的命令。 開源模塊官方發布網站,下載地址:https://pypi.python.org/pypi 下載安裝的模塊會安裝到指定的目錄中: 1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By Sandler 4 5 import sys 6 sys.path 7 ['C:\\Program Files (x86)\\JetBrains\\PyCharm 5.0.4\\helpers\\pydev', 'C:\\Program Files (x86)\\JetBrains\\PyCharm 5.0.4\\helpers\\pydev', 'C:\\Python35\\python35.zip', 'C:\\Python35\\DLLs', 'C:\\Python35\\lib', 'C:\\Python35', 'C:\\Python35\\lib\\site-packages', 'C:\\Users\\Sandler\\PycharmProjects\\PyS'] 8 #安裝的開源模塊會默認安裝到'site-packages'目錄,linux下也在site-packages目錄 如果sys.path路徑列表沒有你想要的路徑,可以通過 sys.path.append('路徑') 添加。 通過os模塊可以獲取各種目錄,例如: 1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By Sandler 4 5 import sys 6 import os 7 pre_path = os.path.abspath('../') 8 sys.path.append(pre_path) 3、導入模塊: 導入模塊有以下幾種方法: 1 import module 2 #導入模塊 3 from module.xx.xx import xx 4 #導入指定目錄下的指定模塊 5 from module.xx.xx import xx as rename 6 #導入指定目錄下的指定模塊并賦予別名 7 from module.xx.xx import * 8 #導入指定目錄下的所有模塊,這種方法可能會導致導入的模塊和現有的函數重名,所以一般不用 導入模塊其實就是告訴Python解釋器去解釋那個py文件 導入一個py文件,解釋器解釋該py文件 導入一個包,解釋器解釋該包下的__init__.py文件舉例: 開源模塊 paramiko的下載和安裝 paramiko是一個用于做遠程控制的模塊,使用該模塊可以對遠程服務器進行命令或文件操作,值得一說的是,fabric和ansible內部的遠程管理就是使用的paramiko來現實。 1、下載安裝 1 # pycrypto,由于 paramiko 模塊內部依賴pycrypto,所以先下載安裝pycrypto 2 3 # 下載安裝 pycrypto 4 wget http://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gz 5 tar -xvf pycrypto-2.6.1.tar.gz 6 cd pycrypto-2.6.1 7 python setup.py build 8 python setup.py install 9 10 # 進入python環境,導入Crypto檢查是否安裝成功 11 12 # 下載安裝 paramiko 13 wget http://files.cnblogs.com/files/wupeiqi/paramiko-1.10.1.tar.gz 14 tar -xvf paramiko-1.10.1.tar.gz 15 cd paramiko-1.10.1 16 python setup.py build 17 python setup.py install 18 19 # 進入python環境,導入paramiko檢查是否安裝成功 2、使用模塊 執行命令 - 通過用戶名和密碼連接服務器 1 #!/usr/bin/env python 2 # -.- coding:utf-8 -.- 3 # By Sandler 4 import paramiko 5 ssh = paramiko.SSHClient() 6 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 7 ssh.connect('192.168.11.11', 22, 'jack', '111111') 8 stdin, stdout, stderr = ssh.exec_command('df') 9 print stdout.read() 10 ssh.close();
執行命令 - 過密鑰鏈接服務器
1 #!/usr/bin/env python 2 # -.- coding:utf-8 -.- 3 # By Sandler 4 import paramiko 5 private_key_path = '/home/auto/.ssh/id_rsa' 6 key = paramiko.RSAKey.from_private_key_file(private_key_path) 7 ssh = paramiko.SSHClient() 8 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 9 ssh.connect('主機名 ', 端口, '用戶名', key) 10 stdin, stdout, stderr = ssh.exec_command('df') 11 print stdout.read() 12 ssh.close()上傳或者下載文件 - 通過用戶名和密碼
1 #!/usr/bin/env python 2 # -.- coding:utf-8 -.- 3 # By Sandler 4 #上傳文件 5 import os,sys 6 import paramiko 7 t = paramiko.Transport(('192.168.11.11',22)) 8 t.connect(username='jack',password='111111') 9 sftp = paramiko.SFTPClient.from_transport(t) 10 sftp.put('/tmp/test.py','/tmp/test1.py') 11 t.close() 12 #下載文件 13 import os,sys 14 import paramiko 15 t = paramiko.Transport(('192.168.11.11',22)) 16 t.connect(username='jack',password='111111') 17 sftp = paramiko.SFTPClient.from_transport(t) 18 sftp.get('/tmp/test.py','/tmp/test1.py') 19 t.close()上傳或下載文件 - 通過密鑰
1 #!/usr/bin/env python 2 # -.- coding:utf-8 -.- 3 # By Sandler 4 #上傳文件 5 import paramiko 6 pravie_key_path = '/home/auto/.ssh/id_rsa' 7 key = paramiko.RSAKey.from_private_key_file(pravie_key_path) 8 t = paramiko.Transport(('192.168.11.11',22)) 9 t.connect(username='jack',pkey=key) 10 sftp = paramiko.SFTPClient.from_transport(t) 11 sftp.put('/tmp/test3.py','/tmp/test4.py') 12 t.close() 13 #下載文件 14 import paramiko 15 pravie_key_path = '/home/auto/.ssh/id_rsa' 16 key = paramiko.RSAKey.from_private_key_file(pravie_key_path) 17 t = paramiko.Transport(('192.168.11.11',22)) 18 t.connect(username='jack',pkey=key) 19 sftp = paramiko.SFTPClient.from_transport(t) 20 sftp.get('/tmp/test3.py','/tmp/test4.py') 21 t.close()內置模塊 TIME模塊 1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By Sandler 4 5 import time 6 import datetime 7 8 print(time.clock()) #返回處理器時間,3.3開始已廢棄 9 print(time.process_time()) #返回處理器時間,3.3開始已廢棄 10 print(time.time()) #返回當前系統時間戳 11 print(time.ctime()) #輸出Tue Jan 26 18:23:48 2016 ,當前系統時間 12 print(time.ctime(time.time()-86640)) #將時間戳轉為字符串格式 13 print(time.gmtime(time.time()-86640)) #將時間戳轉換成struct_time格式 14 print(time.localtime(time.time()-86640)) #將時間戳轉換成struct_time格式,但返回 的本地時間 15 print(time.mktime(time.localtime())) #與time.localtime()功能相反,將struct_time格式轉回成時間戳格式 16 #time.sleep(4) #sleep 17 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #將struct_time格式轉成指定的字符串格式 18 print(time.strptime("2016-01-28","%Y-%m-%d") ) #將字符串格式轉換成struct_time格式 19 20 #datetime module 21 22 print(datetime.date.today()) #輸出格式 2016-01-26 23 print(datetime.date.fromtimestamp(time.time()-864400) ) #2016-01-16 將時間戳轉成日期格式 24 current_time = datetime.datetime.now() # 25 print(current_time) #輸出2016-01-26 19:04:30.335935 26 print(current_time.timetuple()) #返回struct_time格式 27 28 #datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) 29 print(current_time.replace(2014,9,12)) #輸出2014-09-12 19:06:24.074900,返回當前時間,但指定的值將被替換 30 31 str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #將字符串轉換成日期格式 32 new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比現在加10天 33 new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比現在減10天 34 new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比現在減10小時 35 new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比現在+120s 36 print(new_date)
| %a | Locale’s abbreviated weekday name. | ? |
| %A | Locale’s full weekday name. | ? |
| %b | Locale’s abbreviated month name. | ? |
| %B | Locale’s full month name. | ? |
| %c | Locale’s appropriate date and?time?representation. | ? |
| %d | Day of the month as a decimal number [01,31]. | ? |
| %H | Hour (24-hour clock) as a decimal number [00,23]. | ? |
| %I | Hour (12-hour clock) as a decimal number [01,12]. | ? |
| %j | Day of the year as a decimal number [001,366]. | ? |
| %m | Month as a decimal number [01,12]. | ? |
| %M | Minute as a decimal number [00,59]. | ? |
| %p | Locale’s equivalent of either AM or PM. | (1) |
| %S | Second as a decimal number [00,61]. | (2) |
| %U | Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. | (3) |
| %w | Weekday as a decimal number [0(Sunday),6]. | ? |
| %W | Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. | (3) |
| %x | Locale’s appropriate date representation. | ? |
| %X | Locale’s appropriate?time?representation. | ? |
| %y | Year without century as a decimal number [00,99]. | ? |
| %Y | Year with century as a decimal number. | ? |
| %z | Time?zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. | ? |
| %Z | Time?zone name (no characters if no time zone exists). | ? |
| %% | A literal?'%'?character. |
看一下這幾個日志級別分別代表什么意思
| DEBUG | Detailed information, typically of interest only when diagnosing problems. |
| INFO | Confirmation that things are working as expected. |
| WARNING | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
| ERROR | Due to a more serious problem, the software has not been able to perform some function. |
| CRITICAL | A serious error, indicating that the program itself may be unable to continue running. |
其中下面這句中的level=loggin.INFO意思是,把日志紀錄級別設置為INFO,也就是說,只有比日志是INFO或比INFO級別更高的日志才會被紀錄到文件里,在這個例子, 第一條日志是不會被紀錄的,如果希望紀錄debug的日志,那把日志級別改成DEBUG就行了。
1 logging.basicConfig(filename='example.log',level=logging.INFO)感覺上面的日志格式忘記加上時間啦,日志不知道時間怎么行呢,下面就來加上!
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By Sandler 4 5 import logging 6 7 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') 8 logging.warning('is when this event was logged.') 9 10 # 輸出 11 12/12/2010 11:46:36 AM is when this event was logged. 如果想同時把log打印在屏幕和文件日志里,就需要了解一點復雜的知識 了The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.
日志庫采用模塊化的方法,提供了幾種類型的組件:伐木者、處理程序、過濾器和格式器
- Loggers expose the interface that application code directly uses.
- Loggers公開接口,應用程序代碼中直接使用
- Handlers send the log records (created by loggers) to the appropriate destination.
- 處理程序發送日志記錄(由Loggers)到相應的目的地
- Filters provide a finer grained facility for determining which log records to output.
- 過濾器提供更細粒度的功能確定哪些日志記錄輸出
- Formatters specify the layout of log records in the final output.
- 格式器指定的布局在最終的輸出日志記錄
?
1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By Sandler 4 5 import logging 6 7 #create logger 8 logger = logging.getLogger('TEST-LOG') # 定義日志記錄用戶 9 logger.setLevel(logging.DEBUG) # 定義全局日志等級 10 # create console handler and set level to debug 11 ch = logging.StreamHandler() # 定義屏幕輸出 12 ch.setLevel(logging.DEBUG) # 定義屏幕輸出日志等級 13 # create file handler and set level to warning 14 fh = logging.FileHandler("access.log") # 定義日志輸出文件 15 fh.setLevel(logging.WARNING) # 定義文件日志輸出等級 16 # create formatter 17 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 18 # 日志格式化 19 # add formatter to ch and fh 20 ch.setFormatter(formatter) # 日志屏幕輸出格式化 21 fh.setFormatter(formatter) # 日志文件輸出格式化 22 # add ch and fh to logger 23 logger.addHandler(ch) 24 logger.addHandler(fh) 25 # 'application' code 26 logger.debug('debug message') 27 logger.info('info message') 28 logger.warn('warn message') 29 logger.error('error message') 30 logger.critical('critical message')?
?
轉載于:https://www.cnblogs.com/sandler613/p/5562047.html
總結
- 上一篇: html form label标签基础语
- 下一篇: websocket python爬虫_p