日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python—模块

發布時間:2025/5/22 python 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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) DirectiveMeaningNotes
%aLocale’s abbreviated weekday name.?
%ALocale’s full weekday name.?
%bLocale’s abbreviated month name.?
%BLocale’s full month name.?
%cLocale’s appropriate date and?time?representation.?
%dDay of the month as a decimal number [01,31].?
%HHour (24-hour clock) as a decimal number [00,23].?
%IHour (12-hour clock) as a decimal number [01,12].?
%jDay of the year as a decimal number [001,366].?
%mMonth as a decimal number [01,12].?
%MMinute as a decimal number [00,59].?
%pLocale’s equivalent of either AM or PM.(1)
%SSecond as a decimal number [00,61].(2)
%UWeek 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)
%wWeekday as a decimal number [0(Sunday),6].?
%WWeek 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)
%xLocale’s appropriate date representation.?
%XLocale’s appropriate?time?representation.?
%yYear without century as a decimal number [00,99].?
%YYear with century as a decimal number.?
%zTime?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].?
%ZTime?zone name (no characters if no time zone exists).?
%%A literal?'%'?character.
LOGGING模塊 很多程序都有記錄日志的需求,并且日志中包含的信息即有正常的程序訪問日志,還可能有錯誤、警告等信息輸出,python的logging模塊提供了標準的日志接口,你可以通過它存儲各種格式的日志,logging的日志可以分為 debug(), info(), warning(), error() and critical() 5個級別,下面我們看一下怎么用。 最簡單用法 1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By Sandler 4 import logging 5 6 logging.warning("user [alex] attempted wrong password more than 3 times") 7 logging.critical("server is down") 8 9 #輸出 10 WARNING:root:user [alex] attempted wrong password more than 3 times 11 CRITICAL:root:server is down

看一下這幾個日志級別分別代表什么意思

LevelWhen it’s used
DEBUGDetailed information, typically of interest only when diagnosing problems.
INFOConfirmation that things are working as expected.
WARNINGAn 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.
ERRORDue to a more serious problem, the software has not been able to perform some function.
CRITICALA serious error, indicating that the program itself may be unable to continue running.
如果想把日志寫到文件里,也很簡單 1 #!/usr/bin/env python 2 # -.- coding: utf-8 -.- 3 # By Sandler 4 import logging 5 6 logging.basicConfig(filename='example.log',level=logging.INFO) 7 logging.debug('This message should go to the log file') 8 logging.info('So should this') 9 logging.warning('And this, too')

其中下面這句中的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

總結

以上是生活随笔為你收集整理的Python—模块的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。