Files
my_py_tools/public.py
2025-10-18 21:32:31 +08:00

336 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import re
import json
# 提取代码中函数名称
import re
import os
import xml.etree.ElementTree as ET
def debug_print(*args, sep=' ', end='\n', file=None, flush=False):
data = read_json_file('config.json')
try:
debug = data['debug']
except Exception:
debug = 'true'
if debug == 'true':
print(*args, sep=sep, end=end, file=file, flush=flush)
# 提取文件后缀
def extract_file_extension(file_path):
# 正则表达式匹配文件扩展名,即最后一个`.`之后的内容
match = re.search(r'\.([^.]+)$', file_path)
if match:
return match.group(1)
else:
return None
# file_path = r"E:\sesCode_行情\upub\dev_codes\uftbusiness\sysargpub\LS_SYSARGPUB_UMTCONFIG_GET.uftservice"
# print("提取的文件后缀:", extract_file_extension(file_path))
# 提取文件名称
def extract_filename(path):
"""
从路径中提取不带后缀的文件名
:param path: Windows文件路径
:return: 不带后缀的文件名
"""
# 获取路径中的文件名(带后缀)
filename_with_ext = os.path.basename(path)
# 分割文件名和后缀
filename, _ = os.path.splitext(filename_with_ext)
return filename
# 提取文件中的函数名称和功能号
def extract_name_functionNo(xml_str):
# 正则表达式模式
pattern = r'chineseName="([^"]+)".*objectId="([^"]+)"'
# 使用findall方法提取匹配项
matches = re.findall(pattern, xml_str)
if matches:
chinese_name, object_id = matches[0]
return matches[0]
# print(f"chineseName: {chinese_name}")
# print(f"objectId: {object_id}")
else:
# print("没有找到匹配的值")
return None
#xml_str = '<business:Function xmlns:business="http://www.hundsun.com/ares/studio/uft/business/1.0.0" chineseName="AF_融资融券公用_个人集中度限额获取" objectId="3968540">'
# xml_str = '<business:Service xmlns:business="http://www.hundsun.com/ares/studio/uft/business/1.0.0" chineseName="LS_证券行情_行情缓存更新" description="用于行情服务器转UDP更新闭式标志、价格等信息" objectId="970398" sysStatus="系统就绪" id="e088d972-eed4-45a5-aabc-86b2c569986b">'
# chinese_name, object_id = extract_name_functionNo(xml_str)
# print(f"chineseName: {chinese_name}")
# print(f"objectId: {object_id}")
# 读取文件第二行内容
def read_second_line(file_path):
"""
读取指定文件的第二行内容并返回。
参数:
file_path (str): 文件的路径。
返回:
str: 第二行的内容如果没有第二行则返回None。
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
# 跳过第一行
next(file)
# 读取第二行
second_line = next(file, None)
return second_line.strip() if second_line else None
except FileNotFoundError:
print(f"文件 {file_path} 未找到。")
return None
except Exception as e:
print(f"读取文件时发生错误: {e}")
return None
# 读取文件第五行内容
def read_five_line(file_path):
"""
读取指定文件的第二行内容并返回。
参数:
file_path (str): 文件的路径。
返回:
str: 第二行的内容如果没有第二行则返回None。
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
# 跳过第一行
next(file)
next(file)
next(file)
next(file)
# 读取第五行
second_line = next(file, None)
return second_line.strip() if second_line else None
except FileNotFoundError:
print(f"文件 {file_path} 未找到。")
return None
except Exception as e:
print(f"读取文件时发生错误: {e}")
return None
# 提取文件中的函数名称和功能号
def uf20_extract_name_functionNo(xml_str):
# 正则表达式模式
# pattern = r'objectId="([^"]+)".*englishName="([^"]+)"'
# 20250714 fix 修复 englishName为空时提取失败问题
pattern = r'objectId="([^"]*)"[^>]*englishName="([^"]*)"'
# 使用findall方法提取匹配项
matches = re.findall(pattern, xml_str)
if matches:
chinese_name, object_id = matches[0]
return matches[0]
# print(f"chineseName: {chinese_name}")
# print(f"objectId: {object_id}")
else:
# print("没有找到匹配的值")
return None
# 20250807 add 增加判断函数名是否合法
def extract_and_check_prefix(input_str):
# 找到第一个左方括号的位置
bracket_index = input_str.find('[')
if bracket_index != -1:
# 提取第一个 [ 之前的内容
prefix = input_str[:bracket_index]
# 检查是否为 <M>
# 20250823 fix 修复内存<I>等标记无法识别问题(内存与UF20伪代码不一致导致) 检查是否为 <M> <I>或者<IM>
is_m_prefix = prefix == "&lt;M&gt;" or prefix == '' or prefix == "<I>" or prefix == "<IM>" or prefix == "<MI>" or prefix == "<M>"
return prefix, is_m_prefix
else:
# 如果没有 [ ,整个字符串作为前缀
return input_str, input_str == " &lt;M&gt;"
# text = "[LS_外部接口(证券交易)_资金余额更新][][serial_no=@serial_no, enable_balance = @enable_balance, entrust_buy_balance_t = @entrust_buy_balance_t, business_frozen_balance_t = @business_frozen_balance_t][node_no = @partition_no, timeout = @time_out]"
def match_func_name(text):
# 正则表达式匹配第一个中括号内的内容
pattern = r'\[(.*?)\]'
text = text.strip()
if text.startswith("//") or text.startswith("<histories"):
return "None"
# 使用re模块的search函数查找第一个匹配项
match = re.search(pattern, text)
if match:
# 20250825 add 增加判断函数名是否合法
prefix, is_m = extract_and_check_prefix(text)
if is_m == False:
return "None"
content = match.group(1) # group(1)获取第一个括号内的内容
# if content == 'AF_系统公用_动态sql执行':
# debug_print(text)
# debug_print(content)
return content
else:
return "None"
# print(match_func_name(text))
# 判断字符串是否在文件中
def check_string_in_file(file_path, target_string):
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
if target_string in content:
return True
else:
return False
except FileNotFoundError:
print(f"The file {file_path} does not exist.")
return False
except Exception as e:
print(f"An error occurred: {e}")
return False
def load_config(file_path):
"""读取JSON配置文件"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
print(f"错误:文件 {file_path} 不存在")
return None
except json.JSONDecodeError:
print(f"错误:文件 {file_path} 不是有效的JSON格式")
return None
def save_config(file_path, config_data):
"""保存配置到JSON文件"""
try:
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(config_data, file, indent=4, ensure_ascii=False)
print(f"配置已成功保存到 {file_path}")
except Exception as e:
print(f"保存文件时出错:{e}")
'''
# 使用示例
if __name__ == "__main__":
config_file = "config.json" # JSON文件路径
# 读取配置
config = load_config(config_file)
if config:
print("当前配置内容:")
print(json.dumps(config, indent=4, ensure_ascii=False))
# 修改配置示例将debug改为true
config["debug"] = "true"
# 保存修改后的配置
save_config(config_file, config)
'''
# 加载json配置
def read_json_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
except FileNotFoundError:
print(f"File not found: {file_path}")
return None
except json.JSONDecodeError:
print(f"Failed to decode JSON from file: {file_path}")
return None
except Exception as e:
print(f"An error occurred: {e}")
return None
# 修改json配置
def modify_json_config(file_path, dir = '', func = ''):
try:
# 读取 JSON 文件
with open(file_path, 'r', encoding='utf-8') as file:
config = json.load(file)
# 修改配置
if dir != '':
config['dir']= dir
if func != '':
config['function_no'] = func
# 写回修改后的配置
with open(file_path, 'w', encoding='utf-8') as file:
json.dump(config, file, indent=4)
print("Configuration updated successfully.")
except FileNotFoundError:
print(f"File not found: {file_path}")
except json.JSONDecodeError:
print(f"Failed to decode JSON from file: {file_path}")
except Exception as e:
print(f"An error occurred: {e}")
# 20250825 读取UF20的AS的moudel.xml文件内容个性化需求可以用于搜索涉及so
def read_module_xml(file_path):
try:
# 解析XML文件
tree = ET.parse(file_path)
root = tree.getroot()
# 查找info元素
info_element = root.find('info')
if info_element is not None:
# 获取ename和database属性
ename = info_element.get('ename', 'a')
database = info_element.get('database', 'a')
print(f"ename: {ename}")
print(f"database: {database}")
return ename, database
else:
print("未找到info元素")
except ET.ParseError as e:
print(f"XML解析错误: {e}")
except FileNotFoundError:
print(f"文件未找到: {file_path}")
except Exception as e:
print(f"发生错误: {e}")
def read_ls_module_xml(file_path):
try:
# 解析XML文件
tree = ET.parse(file_path)
root = tree.getroot()
# 查找info元素
info_element = root.find('info')
if info_element is not None:
# 获取ename和database属性
ename = info_element.get('ename', '')
print(f"ename: {ename}")
return ename
else:
print("未找到info元素")
except ET.ParseError as e:
print(f"XML解析错误: {e}")
except FileNotFoundError:
print(f"文件未找到: {file_path}")
except Exception as e:
print(f"发生错误: {e}")
def safe_comma_string_to_list(input_str):
"""安全处理逗号分隔字符串包括空字符串和None值"""
if input_str is None:
return []
return [item.strip() for item in input_str.split(';') if item.strip()]