rrdtool:html
rrdtool
可直接用pip install python-rrdtoolpython
import rrdtoolmysql
建立:
create(...)
create(args..): Set up a new Round Robin Database
create filename [--start|-b start time] [--step|-s step] [DS:ds-name:DST:heartbeat:min:max] [RRA:CF:xff:steps:rows]
filename:是rrd的文件名,能夠以rrd結尾。
--step:rrdtool指望每隔多長事件收到一個值,默認是5分鐘。
--start:rrdtool第一個記錄的起始時間,rrdtool不會接收任何數據的時間小於起始時間。例如你在update時給出的時間小於起始時間,則rrdtool會拒絕該值
DS:DS用於定義數據源,是用來存放結果的變量名。該變量名在畫圖時會用到。
DST:用來設置數據源的類型,有COUNTER、GUAGE、DERIVE、ABSOLUTE、COMPUTE等5種類型。
COUNTER:數值必須是遞增的
DERIVE:和COUNTER相似,不過數據可遞增可遞減
ABSOLUTE:他每次假定前一個時間間隔的值是0,而後計算平均值
GAUGE:不作任何變化,直接存入rra中
COMPUTE:他不接收具體值,而是定義一個表達式,而後算出某個值
heartbeat:
min:
max:
RRA:rra指定數據如何存放,他能夠保存不一樣時間間隔的數據。力圖每5分鐘產生一條數據,這樣一小時就是12條,若是每30分鐘一條數據,這樣一小時就是兩條數據,這樣一天,一年下來會有不少條數據,可是rrd數據庫的大小是固定的,因此就有一個合併數據的方式了。這就是rra的功能。合併方式由CF指定。
CF:CF就是用來設置數據合併的功能,有AVERAGE、MAX、MIN、LAST等4種類型,分別表示對PDP取平均、最大、最小、當前值。
xff:xff字段設置一個比例值,rrdtool會把多個PDP合併爲一個CDP,若是這寫PDP中有值爲UNKNOW的PDP,那麼CDP的值該怎麼計算,xff就是設置一個比例,當PDP中UNKNOW的比例超過多少是,就沒法合成正常的CPD,合成的CPD值也爲UNKNOW。
steps:表示多少個PDP合成一個CDP
rows:表示總共存多少個CDP?也就是能夠保存多少數據?
PDP:在每一個規定的時間間隔內rrdtool都會收到一個值,rrdtool在收到該值後,根據DST的設置,會計算出另外一個值,這個值就是PDP。
CDP:rrdtool使用多個PDP合併出一個CDP,也就是執行CF的後果,而後把這個CDP的值存入rra中。
查看第一次/最後一次數據更新時間:linux
first(...)
first(filename): Return the timestamp of the first data sample in an RRD
last(...)
last(filename): Return the timestamp of the last data sample in an RRDios
查看rrd結構信息:
info(...)
info(filename): extract header information from an rrd
取出rrd的值:
fetch(...)
fetch(args..): fetch data from an rrd.
fetch filename CF [--resolution|-r resolution] [--start|-s start] [--end|-e end]
filename:要取出數據的rrd文件
--start:可選,默認是end-1day
--end:可選,默認是now
CF:AVERAGE、MAX、MIN、LAST。前提是你的rrd中有該類型的rra才能夠。sql
更新rrd數據:
update(...)
update(args..): Store a new set of values into the rrd
update filename [--template|-t ds-name[:ds-name]...] N|timestamp:value[:value...] [timestamp:value[:value...] ...]
filename:要更新的rrd文件
--template:
-t ds-name[:ds-name]:設置更新那個DS的數據
N|timestamp:時間戳,表示數據在哪一個時間點採集的,N表示now。
value[:value...]:一個rrd文件能夠有多個DS,因此一次update能夠更新多個value。
update插入值後,並不會有返回,沒法知道插入是否正常,能夠用updatev
帶返回值的插入:
updatev(...)
updatev is called in the same manner as update
和update相似,不過每次插入後會返回一個狀態碼。數據庫
畫圖:
graph(...)
graph(args..): Create a graph based on data from one or several RRD
graph filename [-s|--start seconds] [-e|--end seconds] [-x|--x-grid x-axis grid and label] [-y|--y-grid y-axis grid and label] [--alt-y-grid] [--alt-y-mrtg] [--alt-autoscale] [--alt-autoscale-max] [--units-exponent] value [-v|--vertical-label text] [-w|--width pixels] [-h|--height pixels] [-i|--interlaced] [-f|--imginfo formatstring] [-a|--imgformat GIF|PNG|GD] [-B|--background value] [-O|--overlay value] [-U|--unit value] [-z|--lazy] [-o|--logarithmic] [-u|--upper-limit value] [-l|--lower-limit value] [-g|--no-legend] [-r|--rigid] [--step value] [-b|--base value] [-c|--color COLORTAG#rrggbb] [-t|--title title] [DEF:vname=rrd:ds-name:CF] [CDEF:vname=rpn-expression] [PRINT:vname:CF:format] [GPRINT:vname:CF:format] [COMMENT:text] [HRULE:value#rrggbb[:legend]] [VRULE:time#rrggbb[:legend]] [LINE{1|2|3}:vname[#rrggbb[:legend]]] [AREA:vname[#rrggbb[:legend]]] [STACK:vname[#rrggbb[:legend]]]
filename:圖片的名稱,默認是PNG格式
--start:圖片X軸數據的起始時間
--end:圖片X軸數據的結束時間
--x-grid x-axis grid and label:
--y-grid y-axis grid and label:
--alt-y-grid
--alt-y-mrtg
--alt-autoscale
--alt-autoscale-max
--units-exponent
--vertical-label text Y軸的文字說明
--width pixels X軸的大小
--height pixels Y軸的大小
--interlaced
--imginfo formatstring
--imgformat GIF|PNG|GD 圖片格式
--background value
--overlay value
--unit value
--lazy
--logarithmic
--upper-limit value Y軸數據值的上限,默認會自動調整Y軸的數字
--lower-limit value Y軸數據值的下限
--no-legend 取消圖表下方的圖例
--rigid 嚴格按照upper-limit/lower-limit來繪製
--step value
--base value 默認1K=1000 能夠調整1K=1024
--color COLORTAG#rrggbb
--title title 圖表上方的標題
DEF:vname=rrd:ds-name:CF 定義繪圖用的數據源,也就是從那個RRD中取數據,由於RRA有多種類型,因此須要指定CF
CDEF:vname=rpn-expression 定義合併值,
PRINT:vname:CF:format
GPRINT:vname:CF:format 在圖表的下方輸出最大值、最小值之類
COMMENT:text 用來輸出一些字符串
HRULE:value#rrggbb 在圖表上繪製水平線
VRULE:time#rrggbb 在圖表上繪製垂直線
LINE{1|2|3}:vname 使用線條來繪製vname的數據圖
AREA:vname 使用方塊來繪製vname的數據圖
STACK:vnameexpress
-------------------------------------------------------------------------數組
模塊之psutil操做緩存
psutil
可直接用pip install psutil
psutil.cpu_times() #顯示cpu的整個信息
獲取單項值
psutil.cpu_times() .user #若是要只但看那個的話就在後邊加上.xxx就好了
獲取cpu的邏輯個數
psutil.cpu_count()
獲取cpu的物理個數
psutil.cpu_count( logical=False )
讀取內存信息
linux系統內存利用率信息涉及to-tal(內存總數),used(以使用內存),free(空閒內存),buffers(緩衝使用數)
cache(緩存使用數),swap(交換分區使用數),分別使用psutil.virtual_memory()與psuti.swap_memory()方法獲取
import psutil
mem = psutil.virtual_memory() #獲取內存的完整信息
mem.total #獲取內存總數
mem.free #獲取空閒的內存信息
獲取swap分區信息
psutil.swap_memory()
讀取磁盤參數
磁盤利用率使用psutil.disk_usage方法獲取,磁盤IO信息包括read_count(讀IO數),write_count(寫IO數)
read_bytes(IO寫字節數),read_time(磁盤讀時間),write_time(磁盤寫時間),這些IO信息用psutil.disk_io_counters()
獲取磁盤的完整信息
psutil.disk_partitions()
獲取分區表的參數
psutil.disk_usage('/') #獲取/分區的狀態
獲取硬盤IO總個數
psutil.disk_io_counters()
獲取單個分區IO個數
psutil.disk_io_counters(perdisk=True) #perdisk=True參數獲取單個分區IO個數
讀取網絡信息
網絡信息與磁盤IO信息相似,涉及到幾個關鍵點,包括byes_sent(發送字節數),byte_recv=xxx(接受字節數),
pack-ets_sent=xxx(發送字節數),pack-ets_recv=xxx(接收數據包數),這些網絡信息用psutil.net_io_counters()
psutil.net_io_counters() #獲取網絡總IO信息
psutil.net_io_counters(pernic=True) #pernic=True輸出網絡每一個接口信息--------------------------------------每一個接口信息
獲取當前系統用戶登陸信息
psutil.users()
獲取開機時間
import psutil, datetime
psutil.boot_time() #以linux時間格式返回
datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S") #轉換成天然時間格式
系統進程管理
獲取當前系統的進程信息,獲取當前英語程序的運行狀態,包括進程的啓動時間,查看設置CPU親和度,內存使用率,IO信息
socket鏈接,線程數等
獲取進程信息
psutil模塊在獲取進程方面有很好的支持,使用psutil.pids()方法獲取全部進程的PID,
使用psutil.Process()方法獲取單個進程的名稱,路徑狀態等
查看系統所有進程
psutil.pids()
查看單個進程
p = psutil.Process(2423)
p.name() #進程名
p.exe() #進程的bin路徑
p.cwd() #進程的工做目錄絕對路徑
p.status() #進程狀態
p.create_time() #進程建立時間
p.uids() #進程uid信息
p.gids() #進程的gid信息
p.cpu_times() #進程的cpu時間信息,包括user,system兩個cpu信息
p.cpu_affinity() #get進程cpu親和度,若是要設置cpu親和度,將cpu號做爲參考就好
p.memory_percent() #進程內存利用率
p.memory_info() #進程內存rss,vms信息
p.io_counters() #進程的IO信息,包括讀寫IO數字及參數
p.connectios() #返回進程列表
p.num_threads() #進程開啓的線程數
聽過psutil的Popen方法啓動應用程序,能夠跟蹤程序的相關信息
from subprocess import PIPE
p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"],stdout=PIPE)
p.name()
p.username()
----------------------------------------------------------------------
模塊之_pymysql操做
格式:
conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8")
比較經常使用的參數包括
1.host:數據庫主機名.默認是用本地主機.
2.user:數據庫登錄名.默認是當前用戶.
3.passwd:數據庫登錄的祕密.默認爲空.
4.db:要使用的數據庫名.沒有默認值.
5.port:MySQL服務使用的TCP端口.默認是3306.
6.charset:數據庫編碼.
而後,這個鏈接對象也提供了對事務操做的支持,標準的方法
commit() 提交
rollback() 回滾
3.執行sql語句和接收返回值
cursor=conn.cursor()
n=cursor.execute(sql,param)
首先,咱們用使用鏈接對象得到一個cursor對象,接下來,咱們會使用cursor提供的方法來進行工做.這些方法包括兩大類:1.執行命令,2.接收返回值
cursor用來執行命令的方法:
callproc(self, procname, args):用來執行存儲過程,接收的參數爲存儲過程名和參數列表,返回值爲受影響的行數
execute(self, query, args):執行單條sql語句,接收的參數爲sql語句自己和使用的參數列表,返回值爲受影響的行數
executemany(self, query, args):執行單條sql語句,可是重複執行參數列表裏的參數,返回值爲受影響的行數
nextset(self):移動到下一個結果集
cursor用來接收返回值的方法:
fetchall(self):接收所有的返回結果行.
fetchmany(self, size=None):接收size條返回結果行.若是size的值大於返回的結果行的數量,則會返回cursor.arraysize條數據.
fetchone(self):返回一條結果行.
scroll(self, value, mode='relative'):移動指針到某一行.若是mode='relative',則表示從當前所在行移動value條,若是mode='absolute',則表示從結果集的第一行移動value條.
#再來執行一個查詢的操做
cursor.execute("select * from cdinfo")
#咱們使用了fetchall這個方法.這樣,cds裏保存的將會是查詢返回的所有結果.每條結果都是一個tuple類型的數據,這些tuple組成了一個tuple
cds=cursor.fetchall()
#由於是tuple,因此能夠這樣使用結果集
print cds[0][3]
#或者直接顯示出來,看看結果集的真實樣子
print cds
#若是須要批量的插入數據,就這樣作
sql="insert into cdinfo values(0,%s,%s,%s,%s,%s)"
#每一個值的集合爲一個tuple,整個參數集組成一個tuple,或者list
param=((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2))
#使用executemany方法來批量的插入數據.這真是一個很酷的方法!
n=cursor.executemany(sql,param)
4.關閉數據庫鏈接
須要分別的關閉指針對象和鏈接對象.他們有名字相同的方法
cursor.close()
conn.close()
------------------------------------
鏈接時可設置編碼,以便顯示中文:
>>> conn = pymysql.connect('127.0.0.1','root','111111','mytest',charset ='utf8')
遊標
>>> cur = conn.cursor()
使用數據庫
>>> cur.execute('USE python')
0
執行插入數據,可按字段順序寫入數據
>>> cur.execute("INSERT INTO users VALUES(1,'loutsx'),(2,'小張')")
能夠這樣操做:
cur.execute("INSERT INTO users(id,name) VALUES(3,'中國')")
若是插入的數據有中文,執行腳本會的告警提示,可在建立表的時候設置編碼爲utf8
Warning (from warnings module):
File "C:\Python34\lib\site-packages\pymysql\cursors.py", line 161
result = self._query(query)
Warning: Incorrect string value: '\xE5\xA5\xA5\xE6\x9E\x97...' for column '客戶' at row 1
如下是一個例子,讀取Excel中的數據,並存儲到mysql中:
-----------------------------------------------------
import xlrd
import pymysql
def get_xls():
data = xlrd.open_workbook('s.xls')
sheets = data.sheet_names()
table = data.sheets()[0]
rows = table.nrows
conn = pymysql.connect('127.0.0.1','root','111111','mytest',charset='utf8')------------這裏要設置編碼爲utf8
cur = conn.cursor()
cur.execute("DROP TABLE VRF")
db = 'CREATE TABLE VRF(RD VARCHAR(255),VRF名稱 VARCHAR(255),客戶 VARCHAR(255)) charset ="utf8"'
insert = "INSERT INTO VRF VALUES(%s,%s,%s)"
cur.execute(db)
for i in range(1,rows):
line = table.row_values(i)
print(line)
cur.execute(insert,line)
cur.close()
conn.commit()
conn.close()
get_xls()
print('ok')
------------------------------------------------------
------------------------------------
下面的代碼是一個完整的例子.
#使用sql語句,這裏要接收的參數都用%s佔位符.要注意的是,不管你要插入的數據是什麼類型,佔位符永遠都要用%s
sql="insert into cdinfo values(%s,%s,%s,%s,%s)"
#param應該爲tuple或者list
param=(title,singer,imgurl,url,alpha)
#執行,若是成功,n的值爲1
n=cursor.execute(sql,param)
------------------------------------
執行查詢操做
>>> cur.execute('select * from users')
2
>>> data = cur.fetchall()
>>> data
((1, 'loutsx'), (2, '小張'))
>>> for i in data:
print(i)
(1, 'loutsx')
(2, '小張')
關閉遊標
>>> cur.close()
提交事務,不提交mysql中沒有相關數據
>>> conn.commit()
關閉鏈接
>>> conn.close()
--------------------------------------------------------------------
模塊之_IP地址操做
可直接經過pip下載IPy,或者在Python上下載後安裝
from IPy import *
IPy.INT_TYPES IPy.IPV6_TEST_MAP IPy.MAX_IPV4_ADDRESS IPy.collections IPy.sys
IPy.IP IPy.IPint IPy.MAX_IPV6_ADDRESS IPy.intToIp IPy.types
IPy.IPSet IPy.IPv4ranges IPy.STR_TYPES IPy.parseAddress IPy.xrange
IPy.IPV6_MAP_MASK IPy.IPv6ranges IPy.bisect IPy.py
ips = IPy.IP('192.168.0.0/30')-------可用迭代的方式獲取IP信息
ips.NoPrefixForSingleIp
ips.iptype() 檢查是否公網IP地址
ips.prefixlen() 檢查掩碼的長度
ips.strFullsize() 獲得IP的字符串方式
ips.WantPrefixLen()
ips.len() 獲取IP地址數量,等同於len(ips)
ips.reverseName() 獲取目標IP的反射信息
ips.strHex()
ips.broadcast() 獲取廣播地址
ips.make_net()
ips.reverseNames() 獲取全部IP的反向信息
ips.strNetmask() 獲取目標IP的掩碼,字符串
ips.get_mac()
ips.net()
ips.strBin() 獲取目標IP的二進制方式,字符串
ips.strNormal() 獲取目標IP的信息,字符串,參數有0-3
ips.int() 同 ips.ip ,同ips.strDec(),字符方式
ips.netmask
ips.strCompressed() 獲取目標IP的信息,字符串,等同於ips.strNormal(1)
ips.v46map
ips.overlaps() 確認一個IP是否在另外一段內
ips.version
-----------------------------------------------------------------------
模塊之_excel操做
python Excel模塊
針對 03版excel(xls結尾的),咱們可使用xlrd讀,xlwt包來寫
針對 07版excel(xlsx結尾的),咱們可使用openpyxl來操做讀寫excel
xlrd,xlwt和xlutils是用Python處理Excel文檔(*.xls)的高效率工具。
其中,xlrd只能讀取xls,xlwt只能新建xls(不能夠修改)
xlutils能將xlrd.Book轉爲xlwt.Workbook,從而得以在現有xls的基礎上修改數據,並建立一個新的xls,實現修改
可直接經過pip方式下載
也能夠直接下載:
xlwt的下載地址https://pypi.python.org/pypi/xlwt3
xlrd的下載地址https://pypi.python.org/pypi/xlrd3
openpyx1的下載地址https://pypi.python.org/pypi/openpyxl
#讀取excel使用(支持03)
import xlrd
#寫入excel使用(支持03)
import xlwt3
#讀取execel使用(支持07)
from openpyxl import Workbook
#寫入excel使用(支持07)
from openpyxl import load_workbook
------屬性和方法-----------------------
xlrd
Book(class) 由xlrd.open_work("example.xls")返回
nsheets: sheets數
sheet_names: sheet名稱列表
sheets: sheet列表
sheet_by_index(sheetx): 按序號提取sheet
sheet_by_name(sheet_name): 按名稱提取sheet
Sheet(class) 由Book object相關方法返回
name: sheet名
nrows: 行數
ncols: 列數
cell(rowx,colx): 第rows行colx列的單元格
cell_type(rowx,colx): 數據類型
cell_value(rows,colx): 數值
col(colx): 第colx列全部單元格組成的列表
col_slice(colx,start_rowx=0,end_rowx=None): 第colx列指定單元格組成的列表
col_types(colx,start_rowx=0,end_rowx=None): 第colx列指定單元格數值類型組成的列表
col_values(colx,start_rowx=0,end_rowx=None): 第colx列指定單元格數值組成的列表
row一樣有col的各項操做,此處略去
Cell(class) 由Sheet object(s)相關方法返回
ctype: 一個int型變量,對應不一樣的數值類型
value: 單元格的值
xlwt
Workbook(class) 由xlwt.Workbook()返回
encoding: 編碼方案
add_sheet(sheet_name): 添加sheet
get_sheet(Sheet_name): 選擇sheet
save(file_name): 保存
Worksheet(class) 由Workbook object相關方法返回
write(rows,colx,cell_value,style): 編輯單元格
row(rowx).write(colx,cell_value,style): 編輯行
flush_row_data(): 減小內存壓力,flush以前行不可再修改
col(colx),write(rows,cell_value,style): 編輯列
xlutils
copy: 將xlrd.Book轉爲xlwt.Workbook
styles: 讀取xlrd.Workbook的每個單元格的style
display: 簡單而安全地呈現xlrd讀取的數據
filter: 拆分與整合多個xls文件
margins: 查看錶格稀疏程度
save: 序列化xlrd.Book,轉存爲binary xls或stream
Tips
1. xlrd.open_workbook(fomatting_info=):當formatting_info=Ture,讀取workbook並保留格式
2. xlrd.open_workbook(on_demand=): 當on_demand=True,只有被要求時纔將worksheet載入內存,讀取大文件時使用
3. xlwt.Worksheet.flush_row_data(): 減小內存佔用,被刷新的行不能再訪問或修改,建議每1000行刷新一次(若列不少當調整)
4. xlwt.Workbook(encoding=): 選擇建立的workbook的編碼
<span style="font-family: 'courier new', courier;">
import xlrd
import xlwt
from xlutils.copy import copy
# xlrd
book = xlrd.open_workbook("example.xls", formatting_info=True, on_demand=True)
sheet = book.sheet_by_index(0)
cell = sheet.cell(0,0)
# xlwt
workbook = xlwt.Workbook()
workbook.encoding = "utf-8" # Equals to workbook = xlwt.Workbook(encoding="utf-8")
sheet = workbook.add_sheet("Sheet1", cell_overwrite_ok=True)
style = xlwt.easyxf(
"font: name Arial;"
"pattern: pattern solid, fore_colour red;"
)
sheet.write(0, 0, "content of this cell", style)
sheet.row(0).set_style(style)
workbook.save("example.xls")
#xlutils
workbook = copy(book)
</span>
*********************************************************
******** 2003版本的操做 ********
*********************************************************
打開一個表格
data = xlrd.open_workbook(path)
返回表格中的sheet名稱,多個名稱返回一個列表
sheets=data.sheet_names()
獲取一個工做表
① table = data.sheets()[0] #經過索引順序獲取
② table = data.sheet_by_index(0) #經過索引順序獲取
③ table = data.sheet_by_name(u'Sheet1')#經過名稱獲取
獲取整行和整列的值(返回數組)
複製代碼 代碼以下:
table.row_values(i) ----返回行數的內容,i爲行數索引,返回列表
table.col_values(i) ----返回列數的內容,i爲行數索引,返回列表
獲取行數和列數------這是屬性,沒有()
table.nrows
table.ncols
獲取單元格
table.cell(0,0).value
table.cell(2,3).value
以上命令等同於:
table.cell_value(0,0)
使用行列索引
cell_A1 = table.row(0)[0].value
cell_A2 = table.col(1)[0].value
>>> table.row(0)[1]--------不加Value獲得一個完整的數據
text:'IP Address'
>>> table.row(0)[1].value
'IP Address'
>>> table.row(0)
[text:'訂單編號', text:'IP Address', text:'操做時間']
---------------------------------------------
寫入操做:
打開一個表格,建議用ascii編碼,否則可能會有一些詭異的現象。
wb=xlwt3.Workbook(encoding = 'ascii')
增長一個sheet
sheet=wb.add_sheet("xlwt3數據測試表")
寫入數據table.write(行,列,value)
table.write(0,0,'test')
# 若是對一個單元格重複操做,會引起
# returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0
# 因此在打開時加cell_overwrite_ok=True解決
table = file.add_sheet('sheet name',cell_overwrite_ok=True)
保存到文件中
wb.save(path)
# 另外,使用style
style = xlwt.XFStyle() # 初始化樣式
font = xlwt.Font() # 爲樣式建立字體
font.name = 'Times New Roman'
font.bold = True
style.font = font #爲樣式設置字體
table.write(0, 0, 'some bold Times text', style) # 使用樣式
-----實例----------------
能夠寫入一個不存在的文件中,會自動建立一個文件
>>> wb = xlwt.Workbook()
>>> sheet = wb.add_sheet('另外一個測試')
>>> value = [['姓名','性別','身高','三圍'],['張三','男','190','45'],['李四','男','160','95']]
>>> for i in range(len(value)):
for j in range(len(value[i])):
sheet.write(i,j,value[i][j])
wb.save('d:/2.xls')
print('ok')
ok
ok
ok
>>>
*********************************************************
******** 2007版本的操做 ********
*********************************************************
打開一個表格
data1 = load_workbook(path)
返回表格中的sheet名稱,多個名稱返回一個列表
sheets = data1.get_sheet_names()
獲取一個工做表
stable = data1.get_sheet_by_name('ddd')#經過名稱獲取
row=ws.get_highest_row()
col=ws.get_highest_column()
print("列數: ",ws.get_highest_column())
print("行數: ",ws.get_highest_row())
for i in range(0,row):
for j in range(0,col):
print(ws.rows[i][j].value,"\t\t",end="")
獲取整行和整列的值(返回數組)
複製代碼 代碼以下:
table.row_values(i) ----返回行數的內容,i爲行數索引,返回列表
table.col_values(i) ----返回列數的內容,i爲行數索引,返回列表
獲取行數和列數------這是屬性,沒有()
table.nrows
table.ncols
獲取單元格
table.cell(0,0).value
table.cell(2,3).value
以上命令等同於:
table.cell_value(0,0)
---------------------------------------------------------------------
模塊之_Mail操做
import smtplib
from email.mime.text import MIMEText
sender = 'syother@163.com'
passwd = '1qaz2wsx'
receivers = ['loutsx@163.com']
#鏈接服務器
server = smtplib.SMTP('smtp.163.com',25)
#登陸認證
server.login(sender,passwd)
#郵件內容
msg1 = '''
hello loutsx:
this is python test mail script,
I try the script is sucesess!
'''
#這裏plain是類型,可設置爲html
#格式:MIMEText(_text,_subtype='plain',_charset=None)
msg = MIMEText(msg1,'plain','utf-8')
#定義郵件頭
msg['From'] = 'syother<syother@163.com>'
msg['To'] = u'loutsx <loutsx@163.com>'
msg['Subject'] = u'python mail'
#發送郵件,msg.as_string())這裏將內容轉換爲字串
server.sendmail('syother@163.com','loutsx@163.com',msg.as_string())
'''
------------另外一種方式---------------------------
msg = MIMEText('asdasdf','plain','utf-8')
msg['From'] = 'syother@163.com'
msg ['To'] = 'loutsx@163.com'
msg['Subject'] = u'測試Python'
def mail():
server = smtplib.SMTP('smtp.163.com',25)
server.login('syother@163.com','1qaz2wsx')
server.sendmail('syother@163.com','loutsx@163.com',msg.as_string())
------------------------------------------------------
還能夠發送HTML/IMG的郵件,發送帶附件的郵件
import smtplib
from email.mime.text import MIMEText
sender = 'syother@163.com'
passwd = '1qaz2wsx'
receivers = ['loutsx@163.com']
#鏈接服務器
server = smtplib.SMTP('smtp.163.com',25)
#登陸認證
server.login(sender,passwd)
#郵件內容
msg1 = '''
hello loutsx:
this is python test mail script,
I try the script is sucesess!
'''
#這裏plain是類型,可設置爲html
#格式:MIMEText(_text,_subtype='plain',_charset=None)
msg = MIMEText(msg1,'plain','utf-8')
#定義郵件頭
msg['From'] = 'syother<syother@163.com>'
msg['To'] = u'loutsx <loutsx@163.com>'
msg['Subject'] = u'python mail'
#發送郵件,msg.as_string())這裏將內容轉換爲字串
server.sendmail('syother@163.com','loutsx@163.com',msg.as_string())
'''
------------另外一種方式---------------------------
msg = MIMEText('asdasdf','plain','utf-8')
msg['From'] = 'syother@163.com'
msg ['To'] = 'loutsx@163.com'
msg['Subject'] = u'測試Python'
def mail():
server = smtplib.SMTP('smtp.163.com',25)
server.login('syother@163.com','1qaz2wsx')
server.sendmail('syother@163.com','loutsx@163.com',msg.as_string())
------------------------------------------------------