demo3/visa-scpi-example/parse_inp.py

58 lines
2.0 KiB
Python
Raw Normal View History

import re
import json
import os
def parse_inp_file(file_path):
commands_dict = []
comments_dict = {}
with open(file_path, 'r') as f:
lines = f.readlines()
for line in lines:
parts = line.strip().split(' ')
if len(parts) == 2: # 只处理有一个参数的指令
command, value = parts
# 检查参数是否为数字(包括科学计数法)
if re.match(r'^-?\d+\.?\d*([eE][-+]?\d+)?$', value):
commands_dict.append((command, value)) # 记录指令和参数的元组
# 读取注释文件
2024-12-07 12:12:33 +00:00
comments_file_path = './comments.json'
if not os.path.exists(comments_file_path):
with open(comments_file_path, 'w') as f:
comments_dict = {key: " " for key, _ in commands_dict}
json.dump(comments_dict, f)
else:
with open(comments_file_path, 'r') as f:
comments_dict = json.load(f)
# 保存为JSON文件
2024-12-07 12:12:33 +00:00
with open('./commands.json', 'w') as f:
json.dump([{ "command": cmd, "value": val } for cmd, val in commands_dict], f, indent=2) # 保存所有指令
return commands_dict, comments_dict
def save_comments(comments_dict):
2024-12-07 12:12:33 +00:00
with open('./comments.json', 'w') as f:
json.dump(comments_dict, f, indent=2)
def update_inp_file(file_path, command, new_values):
with open(file_path, 'r') as f:
lines = f.readlines()
updated_lines = []
new_values_set = set(new_values) # 使用集合以避免重复值
for line in lines:
parts = line.strip().split(' ')
if len(parts) == 2 and parts[0] == command:
# 如果当前行的指令在新值中,则更新为新值
if parts[1] in new_values_set:
updated_lines.append(f"{command} {parts[1]}\n")
else:
updated_lines.append(line) # 保留原行
else:
updated_lines.append(line)
with open(file_path, 'w') as f:
f.writelines(updated_lines)