您的位置:首页 > 编程语言 > Python开发

学习记录:python serial 库&excel操作

2016-12-02 00:01 771 查看
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





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python serial