在项目与银行对接过程中,银行侧技术要求将ftp服务器上仅保留7天内的文件数据,同事因为前置机是一台winserver2019的机器,且存在一个处理回单文件的jar包,所以使用python实现了:
1、停止正在运行的jar包进程。
2、脚本运行时根据文件名称判断该文件是否属于7天内的数据,属于则保留,不属于则迁移到其他文件夹中。
3、重新启动jar包程序。
4、日志记录到log文件夹下。
脚本代码如下:
#!/usrusr/bin/python
# -*- coding:utf-8 -*-
import os
import re
import datetime
import shutil
import traceback
import subprocess
import psutil
# 设置源目录和备份目录
source_dir = r'C:\ftp\receiptbill\ICBC'
backup_dir = r'C:\ftp\receiptbill\ICBC_BAK'
log_dir = r'C:\ftp\receiptbill\Log'
jar_path = r'C:\jar_files_path\file-0.0.1-.jar'
# 获取当前日期和时间
current_time = datetime.datetime.now()
log_file_name = f'MoveOldFiles_{current_time.strftime("%Y%m%d_%H%M%S")}.log'
log_file_path = os.path.join(log_dir, log_file_name)
# 定义日志记录函数
def write_log(message, error=None):
if not os.path.exists(log_dir):
os.makedirs(log_dir)
with open(log_file_path, 'a', encoding='utf-8') as log_file:
log_file.write(f'{current_time.strftime("%Y-%m-%d %H:%M:%S")} - {message}\n')
if error:
log_file.write(f'{current_time.strftime("%Y-%m-%d %H:%M:%S")} - 错误信息: {error}\n')
print(f'{current_time.strftime("%Y-%m-%d %H:%M:%S")} - {message}')
if error:
print(f'{current_time.strftime("%Y-%m-%d %H:%M:%S")} - 错误信息: {error}')
# 停止由cmd启动的jar包进程
def stop_jar_process():
try:
write_log("准备停止由cmd启动的jar包进程")
# 查找并终止所有java.exe进程
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
if proc.info['name'] == 'java.exe' and 'file-0.0.1.jar' in ''.join(proc.info['cmdline']):
proc.terminate()
proc.wait() # 等待进程终止
write_log(f"成功停止进程: {proc.info['cmdline']}")
except Exception as e:
write_log(f"停止jar包进程时发生错误", error=str(e))
# 启动file-0.0.1.jar并展示黑窗口
def start_jar():
try:
write_log("准备启动file-0.0.1.jar")
command = f'start cmd.exe /k java -jar "{jar_path}"'
subprocess.Popen(command, shell=True)
write_log(f"成功启动: {jar_path}")
except Exception as e:
write_log(f"启动file-0.0.1.jar时发生错误", error=str(e))
# 检查源目录是否存在
if not os.path.exists(source_dir):
write_log(f"源目录 '{source_dir}' 不存在,请检查路径是否正确。")
exit()
# 停止jar包进程
stop_jar_process()
# 创建备份目录和日志目录(如果不存在)
try:
os.makedirs(backup_dir, exist_ok=True)
os.makedirs(log_dir, exist_ok=True)
except Exception as e:
write_log(f"创建备份目录或日志目录时发生错误: {e}", error=traceback.format_exc())
exit()
# 遍历源目录中的所有文件
try:
write_log("开始遍历源目录中的文件")
for file_name in os.listdir(source_dir):
file_path = os.path.join(source_dir, file_name)
# 检查是否为文件
if not os.path.isfile(file_path):
continue
# 提取文件日期
matchs = file_name.split('_')
if len(matchs) < 5:
write_log(f"文件 '{file_name}' 不符合日期格式,已过滤掉")
continue
file_date_str = matchs[4].replace('.txt', '') if file_name.endswith('.txt') else matchs[4]
try:
file_date = datetime.datetime.strptime(file_date_str, '%Y%m%d')
except ValueError as e:
write_log(f"文件 '{file_name}' 的日期格式不正确,已过滤掉", error=str(e))
continue
# 计算文件日期与当前日期的时间差
time_difference = current_time - file_date
# 判断文件日期是否超过7天
if time_difference.days > 7:
backup_file_path = os.path.join(backup_dir, file_name)
try:
shutil.move(file_path, backup_file_path)
write_log(f"文件 '{file_name}' 已移动到备份目录 '{backup_dir}'")
except Exception as e:
write_log(f"移动文件 '{file_name}' 时发生错误", error=traceback.format_exc())
else:
write_log(f"文件 '{file_name}' 在7天内,保留不动")
write_log("文件遍历和迁移完成")
except Exception as e:
write_log(f"遍历源目录时发生错误: {e}", error=traceback.format_exc())
# 启动file-0.0.1.jar
start_jar()