【python 學習記錄】python serial 庫&excel操作

1,背景

前段時間參與了一個項目,需要對路由設備進行自動化掃描,路由設備獲取到shell的方式很多,但是既然要通用,就必須要使用串口方式,就學習了一下,做個記錄。

由於沒有找到相應通用的方法(lz,rz需要編譯無法自動化),在串口間傳輸文件,因此看看來,最後還是要使用ftp來傳輸,麻煩!僅對串口做個記錄吧。

2,參考文章

比較詳細的記錄:http://icodding.blogspot.jp/2016/05/python-pyserial.html

需要調試的demo:http://www.cnblogs.com/Dreamxi/p/4109450.html

當然官方文檔:http://pyserial.readthedocs.io/en/latest/pyserial.html

github:https://github.com/pyserial/pyserial

3,一個執行命令不斷讀取的小模塊

遠程執行ls命令並獲得回顯結果:

 

#coding=utf-8

import serial
def romote_ls_cmd1():
    ser = serial.Serial("com1", 115200, timeout=2)
    print(ser.is_open)
    if ser.is_open:
        ser.write("ls -l\r\n".encode())
    
        while True:
            data = ser.readline().decode("utf-8")
            #此處也可以使用readlines一次讀出來。
            print(data.strip())
            if len(data) == 0:
                break
    else:
        print("ser is not open")
    ser.close() 
      
#也可以把read(size) + inWaiting()        
def romote_ls_cmd2():
    ser = serial.Serial("com1", 115200, timeout=2)
    print(ser.is_open)
    if ser.is_open:
        while True:
            ser.write("ls -l\r\n".encode())
            size = ser.inWaiting()
            
            if size:
                data = ser.read(size).decode("utf-8")
                print(data.strip())
            if len(data) == 0:
                break
    else:
        print("ser is not open")
    ser.close()      
    

 

4,自動化運行的結果要求使用excel保存

 

因此又接觸了幾個excel的模塊

針對sheet的兩個操作,需要格外記憶一下

4.1 rename sheet

 

http://stackoverflow.com/questions/13785306/change-name-of-an-excel-worksheet-after-reading-the-file-in-python

 

from xlutils.copy import copy
from xlrd import open_workbook

# open the file you're interested
rb = open_workbook('some_document.xlsx')

# copy it to a writable variant
wb = copy(rb)

# find the index of a sheet you wanna rename,
# let's say you wanna rename Sheet1
idx = rb.sheet_names().index('Sheet1')

# now rename the sheet in the writable copy
wb.get_sheet(idx).name = u'Renamed Sheet1'

# save the new spreadsheet
wb.save('new_some_document.xlsx')

# done


4.2 append sheet

 

 

 

http://stackoverflow.com/questions/38081658/adding-a-sheet-to-an-existing-excel-worksheet-without-deleting-other-sheet

 

import xlrd, xlwt
from xlutils.copy import copy as xl_copy

# open existing workbook
rb = xlrd.open_workbook('ex.xls', formatting_info=True)
# make a copy of it
wb = xl_copy(rb)
# add sheet to workbook with existing sheets
Sheet1 = wb.add_sheet('Sheet1')
wb.save('ex.xls')


4.3 讀寫的筆記

 

參考:http://www.cnblogs.com/weiok/p/5369741.html

 

 

 


 

 

 

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章