用Python写一个统计Verilog代码行数的脚本,输入一个带路径的Verilog,首先打开指定的文件并读取全部内容。然后使用正则表达式去除注释,并按行分割并去除空白字符。然后,它查找每个模块实例化语句,并递归计算每个模块的行数,将其加入总行数中,子模块跟当前Verilog文件不在同一个文件夹,最后,它查找每个 include 语句,并递归计算每个 included 文件的行数,将其加入总行数中。最终返回总行数。也同时输出各个子模块的例化名,include文件的对应的代码行数,将输出内容打印在一个python文件里
时间: 2024-02-21 20:00:16 浏览: 190
好的,下面是一个基本的实现,你可以根据需要进行修改和优化:
```python
import os
import re
def count_verilog_lines(file_path):
# 打开文件并读取全部内容
with open(file_path, 'r') as f:
content = f.read()
# 去除注释
content = re.sub(r'//.*', '', content)
content = re.sub(r'/\*[\s\S]*?\*/', '', content)
# 按行分割并去除空白字符
lines = [line.strip() for line in content.split('\n')]
# 查找模块实例化语句并递归计算子模块行数
instance_names = []
total_lines = 0
for line in lines:
if line.startswith('module '):
module_name = line.split()[1].split('(')[0]
instance_names.append(module_name)
elif line.startswith(module_name + ' '):
instance_name = line.split()[1].split('(')[0]
instance_file = line.split()[2].strip(';')
instance_lines = count_verilog_lines(os.path.join(os.path.dirname(file_path), instance_file))
total_lines += instance_lines
print('{}: {} lines'.format(instance_name, instance_lines))
# 查找 include 语句并递归计算 included 文件行数
include_files = []
for line in lines:
if line.startswith('`include '):
include_file = line.split()[1].strip('"')
include_files.append(include_file)
include_lines = count_verilog_lines(os.path.join(os.path.dirname(file_path), include_file))
total_lines += include_lines
print('{}: {} lines'.format(include_file, include_lines))
# 计算当前文件行数
file_lines = len(lines) - len(instance_names)
file_lines -= len(include_files)
total_lines += file_lines
print('Current file: {} lines'.format(file_lines))
# 输出各个子模块的实例化名和 include 文件的代码行数
print('Instance names: {}'.format(instance_names))
print('Include files: {}'.format(include_files))
return total_lines
# 测试
if __name__ == '__main__':
file_path = '/path/to/your/verilog/file'
total_lines = count_verilog_lines(file_path)
print('Total lines: {}'.format(total_lines))
# 将输出内容打印在一个python文件里
with open("output.py", "w") as f:
f.write("Total lines: {}\n".format(total_lines))
f.write("Instance names: {}\n".format(instance_names))
f.write("Include files: {}\n".format(include_files))
```
阅读全文