1. 程式人生 > >python's twenty-sixth day for me 模塊

python's twenty-sixth day for me 模塊

Matter named 用戶 字符 位置 move dict info gin

configparser 模塊:

  該模塊適用於配置文件的格式與windows ini文件類似,可以包含一個或多個節(section),每個節可以有多個參數(鍵 = 值)。

  創建文件:

#   創建文件
import configparser
config = configparser.ConfigParser()
config[DEFAULT] = {SeverAliveInterval:45,
                     Compression:yes,
                     CompressionLevel:9,
                     
ForwardXll:yes } config[bitbucket.org] = {User:hg} config[topsecret.server.com] = {Host Port:50022,ForwardXll:no} with open(example.ini,w) as configfile: config.write(configfile)

  查找文件:

#   查找文件
import configparser
config = configparser.ConfigParser()
# 查找文件內容,基於字典的形式。 print(config.sections()) # [] 如果沒有指定文件路徑,則打印的就是空列表 config.read(example.ini) print(config.sections()) # [‘bitbucket.org‘, ‘topsecret.server.com‘] 除了DEFAULT的所有小節名 print(bytebong.com in config) # False 查詢小節名,存在返回True不存在則返回Falese print(bitbucket.org in config) # True
print(config[bitbucket.org][user]) # hg print(config[DEFAULT][compression]) # yes print(config[topsecret.server.com][ForwardXll]) # no print(config[bitbucket.org]) # <Section: bitbucket.org> 打印對象名[小節名] 相當於返回一個叠代器 for i in config[bitbucket.org]: print(i) # 將文件中指定小節的鍵打印出來,若是有DEFAULT則會將DEFAULT的鍵默認打印出來。 # user # severaliveinterval # compressionlevel # forwardxll # forwardxll print(config.options(bitbucket.org)) # [‘user‘, ‘forwardxll‘, ‘compression‘, ‘severaliveinterval‘, ‘compressionlevel‘] # 將 小節名下的鍵以列表形式打印出來,若是有default則將default中的鍵也添加到列表中。 print(config.get(bitbucket.org,compression)) # yes get方法Section下的key對應的value

  增刪改操作:把文件內容取出來更改所以要寫入一個新文件中,才能更改。

import configparser
config = configparser.ConfigParser()
config.read(example.ini)
config.add_section(yuan)

config.remove_section(bitbucket.org)
config.remove_option(topsecret.server.com,forwardXll)

config.set(topsecret.server.com,k1,1111)
config.set(yuan,k2,2222)
config.write(open(new2.ini,w))  # 新建一個文件,把更改後的文件寫入。

logging 模塊:

  1,記錄日誌的模塊。

  2,它不能自己打印內容,只能根據程序員寫的代碼來完成功能。

  3,logging模塊提供五種日誌級別從低到高排序:debug , info , warning , error , critical

  4,只顯示一些基礎信息,可以對顯示的格式做一些配置。

  函數式簡單配置:

# 函數式見配置
import logging
logging.debug(debug message)
logging.info(info message)
logging.warning(warning message)
logging.error(error message)
logging.critical(critical message)

# WARNING:root:warning message
# ERROR:root:error message
# CRITICAL:root:critical message
# 默認打印warning級別以上的所有日誌。
# 日誌級別:criticla > error > warning > info> debug

  靈活配置日誌級別,日誌格式,輸出位置:

import logging
# 默認情況下 只顯示 警告 及警告級別以上信息
logging.basicConfig(level=logging.DEBUG,
                    format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s,
                    datefmt=%a, %d %b %y %H:%M:%S,
                    filename = userinfo.log
                    )
logging.debug(debug message)       # debug 調試模式 級別最低
logging.info(info message)         # info  顯示正常信息
logging.warning(warning message)   # warning 顯示警告信息
logging.error(error message)       # error 顯示錯誤信息
logging.critical(critical message)

# 缺點:編碼格式不能設置。
#       不能同時輸出到文件和屏幕。

  logger對象配置:

import logging
# logging.basicConfig(level = logging.DEBUG)
logger = logging.getLogger()
fh = logging.FileHandler(log,encoding=utf-8)    # 創建一個handler,用於寫入日誌文件。
ch = logging.StreamHandler()    # 創建一個handler,用於輸出控制臺
formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s)
fh.setLevel(level=logging.DEBUG)    # 對文件句柄設置等級。

fh.setFormatter(formatter)     # 格式和文件句柄或者屏幕句柄關聯
ch.setFormatter(formatter)
logger.addHandler(fh)   # logger對象可以添加多個fh和ch對象,和logger(對象)關聯的只有句柄。
logger.addHandler(ch)

logging.debug(debug message)       # debug 調試模式 級別最低
logging.info(info message)         # info  顯示正常信息
logging.warning(warning message)   # warning 顯示警告信息
logging.error(error message)       # error 顯示錯誤信息
logging.critical(critical message)

  配置參數:

技術分享圖片
logging.basicConfig()函數中可通過具體參數來更改logging模塊默認行為,可用參數有:

filename:用指定的文件名創建FiledHandler,這樣日誌會被存儲在指定的文件中。
filemode:文件打開方式,在指定了filename時使用這個參數,默認值為“a”還可指定為“w”。
format:指定handler使用的日誌顯示格式。
datefmt:指定日期時間格式。
level:設置rootlogger(後邊會講解具體概念)的日誌級別
stream:用指定的stream創建StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默認為sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。

format參數中可能用到的格式化串:
%(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用戶輸出的消息
配置參數

collections 模塊:

  namedtuple:

from collections import namedtuple
Point = namedtuple(Point,[x,y])
p = Point(1,2)
print(p.x)      # 1
print(p.y)      # 2

  deque:

from collections import deque
# 雙端隊列
dq = deque()
dq.append(1)    # 默認依次往右添加。
dq.append(2)
dq.append(3)
print(dq)   # deque([1, 2, 3])  類似於列表,但不是列表。
print(dq.pop()) # 3 默認刪除最後一個添加進去的。
print(dq.popleft())    # 從左側開始刪除。
dq.appendleft(4)        # 從左側添加
dq.appendleft(5)
print(dq)   # deque([5, 4, 2])

  OrderedDict:

from collections import OrderedDict
dic = OrderedDict([[k1,v1],[k3,v3],[k2,v2]])
print(dic)  # OrderedDict([(‘k1‘, ‘v1‘), (‘k3‘, ‘v1‘), (‘k2‘, ‘v1‘)])
dic = OrderedDict([(k1,v1),(k2,v2),(k3,v3)])
print(dic)  # OrderedDic

#子元素是列表或者元素都可以!

python's twenty-sixth day for me 模塊