InitMonthSqlFunction.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import os
  2. import shutil
  3. from datetime import datetime, timedelta
  4. def print_sql_files():
  5. """返回 Origin 目录下所有 sql 文件的内容字典
  6. Returns:
  7. dict: 字典,key 是文件名,value 是文件内容
  8. """
  9. # 获取当前文件所在目录
  10. current_dir = os.path.dirname(os.path.abspath(__file__))
  11. # 构建 Origin 目录路径
  12. origin_dir = os.path.join(current_dir, "Origin")
  13. # 创建结果字典
  14. sql_files_dict = {}
  15. # 遍历 Origin 目录
  16. for file_name in os.listdir(origin_dir):
  17. # 检查是否为 .sql 文件
  18. if file_name.endswith(".sql"):
  19. # 构建完整路径
  20. full_path = os.path.join(origin_dir, file_name)
  21. # 读取文件内容
  22. try:
  23. with open(full_path, 'r', encoding='utf-8') as f:
  24. content = f.read()
  25. sql_files_dict[file_name] = content
  26. except Exception as e:
  27. print(f"读取文件 {file_name} 时出错: {e}")
  28. return sql_files_dict
  29. def get_month_data(month=None):
  30. """获取并返回指定月份或当前月份的相关数据
  31. Args:
  32. month: 可选参数,格式为 YYYYMM (如 "202602"),如果不传则使用当前月份
  33. 返回格式:
  34. ["202602", "202603", "202601", "2026-02"]
  35. 分别对应:指定月份、次月、上月、指定月份(带分隔符)
  36. """
  37. # 获取日期
  38. if month:
  39. # 如果传入了月份,解析为日期
  40. # 解析 YYYYMM 格式的月份
  41. year = int(month[:4])
  42. month_num = int(month[4:])
  43. now = datetime(year, month_num, 1)
  44. else:
  45. # 如果没有传入月份,使用当前日期
  46. now = datetime.now()
  47. # 当前月份 (格式: YYYYMM)
  48. current_month = now.strftime("%Y%m")
  49. # 次月
  50. next_month = (now.replace(day=28) + timedelta(days=4)).strftime("%Y%m")
  51. # 上月
  52. last_month = (now.replace(day=1) - timedelta(days=1)).strftime("%Y%m")
  53. # 当前月份 (带分隔符,格式: YYYY-MM)
  54. current_month_with_separator = now.strftime("%Y-%m")
  55. return [current_month, next_month, last_month, current_month_with_separator]
  56. def ensure_directory(directory_path):
  57. """判断指定目录是否存在,不存在则创建,存在则删除里面的内容
  58. Args:
  59. directory_path: 要检查的目录路径
  60. """
  61. print(f"处理目录: {directory_path}")
  62. # 检查目录是否存在
  63. if not os.path.exists(directory_path):
  64. # 目录不存在,创建目录
  65. os.makedirs(directory_path)
  66. print(f"目录不存在,已创建: {directory_path}")
  67. else:
  68. # 目录存在,删除里面的内容
  69. print(f"目录存在,删除里面的内容")
  70. for item in os.listdir(directory_path):
  71. item_path = os.path.join(directory_path, item)
  72. if os.path.isfile(item_path):
  73. os.remove(item_path)
  74. print(f"删除文件: {item_path}")
  75. elif os.path.isdir(item_path):
  76. shutil.rmtree(item_path)
  77. print(f"删除目录: {item_path}")
  78. def generate_sql_files(month=None):
  79. """生成SQL文件
  80. Args:
  81. month: 可选参数,格式为 YYYYMM (如 "202602"),如果不传则使用当前月份
  82. 步骤:
  83. 1. 调用 ensure_directory 确保 SqlOut 目录存在且为空
  84. 2. 调用 get_month_data 读取参数列表
  85. 3. 调用 print_sql_files 获得文件键值对
  86. 4. 遍历步骤3的返回值,每条把结果按照步骤2的返回值进行string替换其中{0}{1}{2}{3}的值
  87. 5. 按照key值输出到步骤1所说的目录里
  88. """
  89. # 对传入的月份参数进行格式校验
  90. if month:
  91. # 检查长度是否为6位
  92. if len(month) != 6:
  93. raise ValueError(f"月份参数格式错误: {month},应为6位数字,格式为 YYYYMM")
  94. # 检查是否为数字
  95. if not month.isdigit():
  96. raise ValueError(f"月份参数格式错误: {month},应为数字")
  97. # 检查月份是否在有效范围内 (1-12)
  98. month_num = int(month[4:])
  99. if month_num < 1 or month_num > 12:
  100. raise ValueError(f"月份参数格式错误: {month},月份应在 1-12 之间")
  101. # 步骤1: 确保 SqlOut 目录存在且为空
  102. current_dir = os.path.dirname(os.path.abspath(__file__))
  103. sql_out_dir = os.path.join(current_dir, "SqlOut")
  104. ensure_directory(sql_out_dir)
  105. # 步骤2: 读取参数列表
  106. month_data = get_month_data(month)
  107. print(f"\n获取到的月份参数: {month_data}")
  108. # 步骤3: 获得文件键值对
  109. sql_files = print_sql_files()
  110. print(f"\n获取到 {len(sql_files)} 个 SQL 文件")
  111. # 步骤4-5: 处理并输出文件
  112. print("\n开始处理并输出文件:")
  113. for file_name, content in sql_files.items():
  114. # 替换内容中的 {0}{1}{2}{3}
  115. try:
  116. # 使用 str.format 方法替换占位符
  117. replaced_content = content.format(*month_data)
  118. # 构建输出文件路径
  119. output_path = os.path.join(sql_out_dir, file_name)
  120. # 写入文件
  121. with open(output_path, 'w', encoding='utf-8') as f:
  122. f.write(replaced_content)
  123. print(f"成功输出文件: {file_name}")
  124. except Exception as e:
  125. print(f"处理文件 {file_name} 时出错: {e}")
  126. import sys
  127. if __name__ == "__main__":
  128. # 检查命令行参数
  129. if len(sys.argv) > 1:
  130. # 获取传入的月份参数
  131. month = sys.argv[1]
  132. print(f"使用传入的月份参数: {month}")
  133. generate_sql_files(month)
  134. else:
  135. # 没有传入参数,使用当前月份
  136. print("没有传入月份参数,使用当前月份")
  137. generate_sql_files()