本文使用python编写脚本,读取.ini配置文件中源码路径,对C++源码进行代码规范静态分析,并生成分析结果报告。使用谷歌的开源工具cpplint.py ,所检测代码符合谷歌代码规范。
cpplint.py默认支持的文件格式包含:‘c’, ‘cc’, ‘cpp’, ‘cxx’, ‘c++’, 'cu’及其头文件,默认不支持.hpp文件。
python代码最好使用notepad编写,视图——显示符号——显示空格和制表符,注意缩进使用空格键
一、在编写脚本前先熟悉一下python-读取配置文件
1 基本的读取操作:
-read(filename) 直接读取文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数
2 基本的写入操作:
-write(fp) 将config对象写入至某个 .init 格式的文件 Write an .ini-format representation of the configuration state.
-add_section(section) 添加一个新的section
-set( section, option, value 对section中的option进行设置,需要调用write将内容写入配置文件
-remove_section(section) 删除某个 section
-remove_option(section, option)
二、然后开始编写脚本
- 批处理python文件
import configparser
import os
def get_file(root_path, all_files):
files = os.listdir(root_path)
for file in files:
if not os.path.isdir(root_path + '/' + file): # not a dir
all_files.append(root_path + '/' + file)
else: # is a dir
get_file((root_path+'/'+file),all_files)
return all_files
cf = configparser.ConfigParser()
cf.read("src_path.ini") # 读取配置文件,如果写文件的绝对路径,就可以不用os模块
for item in cf.options('srcpath'):
rootdir = cf.get('srcpath', item)
list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
print("len(list)", len(list),rootdir)
paths = get_file(rootdir,[]);
for path in paths:
str = "python cpplint.py %(path)s --counting=toplevel --output=vs7 >> %(item)s 2>&1"%{'path':path, 'item':item}
print("==========path==========", path)
os.system(str)
print("------end--------")
- src_path.ini配置文件
[srcpath]
report1.txt=D:\code_standard\code_standard1
report2.txt=D:\code_standard\code_standard2
report3.txt=D:\code_standard\code_standard3
report4.txt=D:\code_standard\code_standard4
- 说明
report1.txt 是静态分析产生的结果报告名称
D:\code_standard\code_standard1 是代码路径