读取config文件夹下的config文件,多线程调用程序,备份数据。
# -*- coding: UTF-8 -*-
import os
import threading
import time
import subprocess
import datetime
import shutil
def get_config(path):
baseconfig = []
basepath = []
for root, dirs, files in os.walk(path):
if 'config' in root:
for i in files:
if 'config' in i:
# 获取上层的父目录
basepath.append(os.path.dirname(root))
baseconfig.append(i)
# print(basepath, "****", baseconfig)
return basepath, baseconfig
def nrtkrun(root, config, nrtkspe):
con = str(config).split('.')
# 获取工作目录的盘符
cmd1 = os.path.splitdrive(root)[0]
cmd2 = 'cd ' + root
cmd3 = nrtkspe + ' config\\' + config
# 拼接命令行,使用cmd /c来执行整个命令字符串
command = 'cmd /c ' + cmd1 + ' && ' + cmd2 + ' && ' + cmd3
# print(command)
# 创建一个子进程,并使用PIPE来获取输出
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
# 使用循环来实时读取输出
with process.stdout:
for line in iter(process.stdout.readline, ''): # 当没有更多行时,迭代器会返回空字符串
if 'POS:' in line:
print(con[0], line, end='') # 打印输出行,end=''确保不换行
# 等待进程结束
process.wait()
def movefile(path):
# 创建数据备份目录
databackuppath = os.path.join(path, 'Dababackup')
os.makedirs(databackuppath, exist_ok=True)
# 指定子目录的名称
now = datetime.datetime.now()
child_dir = str(now.strftime('%Y%m%d_%H%M%S'))
# 拼接子目录的完整路径
child_dir_path = os.path.join(databackuppath, child_dir)
# 创建子目录
os.makedirs(child_dir_path, exist_ok=True)
outpath = os.path.join(path, 'out')
for root, dirs, files in os.walk(outpath):
for file in files:
src_file_path = os.path.join(outpath, file)
if os.path.exists(src_file_path):
# 移动文件
shutil.move(src_file_path, child_dir_path)
# print(f"移动文件完成:", src_file_path)
time.sleep(5)
print(f"{datetime.datetime.now()}:移动文件完毕")
def runtime(n):
# path = os.getcwd()
path = r'E:\nrtk_spe\RTK-MONITOR-20240912'
# 备份数据,避免被覆盖
movefile(path)
# 设置默认的spe程序名称
nrtkspe = 'RTK-MONITOR-20240912.exe'
# 获取工作目录下的spe程序名称
for file in os.walk(path):
if 'RTK-MONITOR' in file:
nrtkspe = file
else:
nrtkspe = nrtkspe
# 获取路径和配置文件
rc = get_config(path)
basepath = rc[0]
baseconfig = rc[1]
# 调用进程批量运行
for i in range(len(baseconfig)):
thread = threading.Thread(target=nrtkrun, args=(basepath[i], baseconfig[i], nrtkspe))
thread.start()
# 运行n秒后,杀死任务
time.sleep(n)
# /f强制,/t子进程,/im程序名称
os.system('taskkill /f /t /im ' + nrtkspe)
if __name__ == '__main__':
while True:
runtime(600)
运行: