源文件:通过nmon命令生成的nmon数据文件(已有的)。
目标文件:使用python代码解析成带图的excel。
经过深入的调研,就我自己调研的方案有两种。
第一种依赖库:win32com
第二种依赖库:xlwings
这两个库之前关系:经过各方面的查阅以及官方文档阅读,xlwings相当于在win32com等库的封装,由于win32com的接口等不太好使用,对新手很不友好,于是xlwings在这个win32com基础外加其他的一些库,封装了一层,对外开放了对应的使用文档(个人理解)。
第一种方案代码:
# -*- coding:utf-8 -*-
import os
import win32com.client
import pythoncom
import win32api
def get_nmon_result_file(micro_file, nmon_files, save_path=""):
x1 = win32com.client.Dispatch("Excel.Application")
x1.Visible = True
x1.DisplayAlerts = False
nmon_tuple = [0]
result_file = []
for index in range(0, len(nmon_files)):
check_file(nmon_files[index], nmon_tuple)
y = x1.Workbooks.Open(micro_file)
if save_path != "" and len(nmon_files) == 1:
result_file.append(save_path)
elif save_path == "" and len(nmon_files) == 1:
save_path = nmon_files[0] + ".xlsx"
result_file.append(save_path)
else:
for i in range(0, len(nmon_files)):
result_file.append(nmon_files[i] + ".xlsx")
try:
# Main代表nmon analyser v46.xlsm VB函数入库名称
x1.Application.Run("Main", 0, save_path, nmon_tuple)
y.Save()
y.Close(SaveChanges=0)
except pythoncom.com_error as error:
print(win32api.FormatMessage(error.excepinfo[0]))
finally:
x1.Quit()
x1 = None
return result_file
def check_file(nmon_files, file_tuple):
if os.path.isfile(nmon_files):
file_tuple.append(nmon_files)
else:
file_list = os.listdir(nmon_files)
for index in range(0, len(file_list)):
file_name = os.path.join(nmon_files, file_list[index])
check_file(file_name, file_tuple)
if __name__ == '__main__':
get_nmon_result_file(
micro_file=os.getcwd() + '\\nmon analyser v46.xlsm',
nmon_files=[os.getcwd() + '\\test.nmon']
)
第二种方案:
# -*- coding:utf-8 -*-
import os
if __name__ == '__main__':
nmon_files = [os.getcwd() + '\\test.nmon']
nmon_tuple = [0, os.getcwd() + '\\test.nmon']
save_path = os.getcwd() + '\\test.nmon.xlsx'
import xlwings as xw
app = xw.Book('nmon analyser v46.xlsm')
macro = app.macro('Main')
print(save_path)
try:
macro(0, save_path, nmon_tuple)
app.save()
app.close()
except Exception as e:
print(str(e))
pass
以上两种方案都能实现将nmon文件解析成带图的excel。
其中最核心的是nmon analyser v46.xlsm里的VB代码,以上两种方案都是通过调用xlsm文件里的VB函数对nmon文件进行解析,生成了解析的excel文件。
不过遗憾的是由于以上2种方案都是通过与Excel实例进行交互,完成VB函数对nmon文件内容的解析,再生成图表,所以都是只能在Windows环境进行使用,Linux环境无法安装。
也许在Linux环境安装wine(一个能够在多种 POSIX-compliant 操作系统(诸如 Linux,Mac OSX 及 BSD 等)上运行 Windows 应用的兼容层)可以实现,但是wine的一些win32 API是不完善的,可能无法达到解析的目的。
我使用的python环境:3.6.7
个人推荐使用第一种,第一种方案可以完成python代码运行无阻碍,无需手动操作excel弹出的各种窗体。
该xlsm文件对应的VB语言部分经过修改,完成了自动保存等效果,使得python代码在执行的过程中,不出现卡死现象。
nmon analyser v46.xlsm文件:https://download.csdn.net/download/qq_42631707/12408336
也许,我们通过调用已有的xlsm完成交互,这种方案在Linux上就不可行,如果想要在Linux完成解析成带图的excel,只有把xlsm里的VB代码理解后,自己通过openpyxl、xlswriter、xlwt等库自己去解析成带图的excel(个人推荐使用openpyxl、xlswriter)。