# -*-coding:utf-8 -*-
# Description:配置修改通用方法,目前支持格式:sh properties yml ini
import ruamel.yaml
def modify_shell_variable(file_path, variable_name, new_value):
'''
sh文件配置修改通用方法
'''
with open(file_path, 'r',encoding="UTF-8") as file:
lines = file.readlines()
modified_lines = []
for line in lines:
if line.startswith(f'{variable_name}='):
# 如果原始变量值不包含双引号,则不添加双引号
if '"' not in line:
modified_line = f'{variable_name}={new_value}\n'
else:
start_index = line.index('"') + 1
end_index = line.rindex('"')
modified_line = line[:start_index] + new_value + line[end_index:]
else:
modified_line = line
modified_lines.append(modified_line)
with open(file_path, 'w',encoding="UTF-8") as file:
file.writelines(modified_lines)
print(f"已将配置文件{file_path}中参数{variable_name}修改为{new_value}")
def modify_property_config(file_path, key, new_value, encoding='UTF-8'):
properties = []
modified = False
with open(file_path, 'r', encoding=encoding) as file:
for line in file:
line = line.strip()
if line and not line.startswith('#') and not line.startswith('!'):
if '=' in line:
prop_key, prop_value = line.split('=', 1)
if prop_key.strip() == key:
line = f"{prop_key.strip()}={new_value}"
modified = True
properties.append(line)
if not modified:
properties.append(f"{key}={new_value}")
with open(file_path, 'w', encoding=encoding) as file:
file.write('\n'.join(properties))
print(f"已将配置文件{file_path}中参数{key}修改为{new_value}")
def modify_yaml_config(yaml_file, key, new_value):
def process_document(document):
keys = key.split('.')
current = document
for k in keys[:-1]:
current = current[k]
last_key = keys[-1]
if last_key not in current:
# print("不存在此参数")
pass
else:
current[last_key] = new_value
# print("修改后", current)
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.indent(mapping=2, sequence=4, offset=2)
with open(yaml_file, 'r', encoding="UTF-8") as stream:
documents = list(yaml.load_all(stream))
for document in documents:
process_document(document)
with open(yaml_file, 'w', encoding="UTF-8") as stream:
yaml.dump_all(documents, stream)
print(f"已将配置文件{yaml_file}中参数{key}修改为{new_value}")
def update_ini_config(file_path, variable_name, new_value):
with open(file_path, 'r', encoding="UTF-8") as file:
lines = file.readlines()
modified_lines = []
for line in lines:
if line.startswith(f'{variable_name}='):
# 如果原始变量值不包含双引号,则不添加双引号
if '"' not in line:
modified_line = f'{variable_name}={new_value}\n'
else:
start_index = line.index('"') + 1
end_index = line.rindex('"')
modified_line = line[:start_index] + new_value + line[end_index:]
else:
modified_line = line
modified_lines.append(modified_line)
with open(file_path, 'w', encoding="UTF-8") as file:
file.writelines(modified_lines)
print(f"已将配置文件{file_path}中参数{variable_name}修改为{new_value}")
.sh .properties .yml .ini格式的配置文件修改
于 2024-04-09 13:52:27 首次发布