共计 4596 个字符,预计需要花费 12 分钟才能阅读完成。
Bililive-go是一个支持多种直播平台的直播录制工具。
脚本内容
需要安装python,示例关键字“3D”
import os
import logging
from datetime import datetime
import subprocess
import time
# 配置日志记录
log_file = "script_log.txt"
# 日志记录器配置
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# 自定义处理器
class LimitedLinesFileHandler(logging.FileHandler):
def emit(self, record):
"""写入日志并保持最近的10条记录"""
log_message = self.format(record)
if os.path.isfile(self.baseFilename):
with open(self.baseFilename, 'r') as f:
lines = f.readlines()
else:
lines = []
lines.append(log_message + '\n')
if len(lines) > 10:
lines = lines[-10:]
with open(self.baseFilename, 'w') as f:
f.writelines(lines)
handler = LimitedLinesFileHandler(log_file)
formatter = logging.Formatter('%(asctime)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# 设置要检查的文件夹路径和 Docker 容器名称
folder_path = "自定义路径/bililive-go/video/哔哩哔哩"
container_name = "bililive-go"
status_file = "status_file.txt"
def get_last_execution_times():
"""读取上次执行记录的时间"""
if os.path.isfile(status_file):
with open(status_file, 'r') as file:
lines = file.readlines()
last_execution_time = lines[0].split(': ')[1].strip() if len(lines) > 0 else ""
container_stop_time = lines[1].split(': ')[1].strip() if len(lines) > 1 else ""
return last_execution_time, container_stop_time
return "", ""
def write_status_file(last_execution_time, container_stop_time):
"""写入状态文件"""
with open(status_file, 'w') as file:
file.write(f"Last Execution Time: {last_execution_time}\n")
file.write(f"Container Stop Time: {container_stop_time}\n")
def find_video_files(path):
"""查找视频文件(MP4, FLV, TS)"""
video_extensions = ('.mp4', '.flv', '.ts')
video_files = [os.path.join(root, file)
for root, dirs, files in os.walk(path)
for file in files
if file.endswith(video_extensions)]
return video_files
def is_within_time_range(current_time):
"""检查是否在扫描时间段内"""
start_time = current_time.replace(hour=17, minute=50, second=0, microsecond=0)
end_time = current_time.replace(hour=23, minute=59, second=59, microsecond=999999)
return start_time <= current_time <= end_time
def check_and_manage_files(video_files, current_time):
"""检查视频文件并执行操作"""
for file in video_files:
# 检查文件名是否包含“3D”
if "3D" in file:
logger.info(f"找到3D视频: {file},不执行任何操作。")
continue
# 检查文件的修改时间
file_mod_time = datetime.fromtimestamp(os.path.getmtime(file))
time_diff = (current_time - file_mod_time).total_seconds()
if time_diff < 600:
# 关闭 Docker 容器
logger.info(f"文件 {file} 的修改时间小于600秒,尝试关闭容器并删除文件。")
if subprocess.run(['docker', 'stop', container_name]).returncode == 0:
logger.info(f"容器 {container_name} 已停止。")
container_stop_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
write_status_file(current_time.strftime("%Y-%m-%d %H:%M:%S"), container_stop_time)
try:
os.remove(file)
logger.info(f"文件 {file} 已删除。")
except OSError as e:
logger.error(f"删除文件 {file} 失败: {e}")
else:
logger.error(f"停止容器 {container_name} 失败。")
return
def manage_container_status(current_time):
"""管理容器状态"""
container_status = subprocess.run(['docker', 'inspect', '-f', '{{.State.Running}}', container_name],
capture_output=True, text=True).stdout.strip()
if container_status == "true":
logger.info(f"{container_name} 运行正常,脚本退出。")
print(f"{container_name} 运行正常,脚本退出。")
return True
else:
logger.info(f"容器 {container_name} 当前未运行,尝试启动...")
if subprocess.run(['docker', 'start', container_name]).returncode == 0:
logger.info(f"容器 {container_name} 已启动。")
# 等待30秒后再执行文件检查
time.sleep(30)
return False
else:
logger.error(f"启动容器 {container_name} 失败。")
return False
def main():
current_time = datetime.now()
current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S")
last_execution_time_str, container_stop_time_str = get_last_execution_times()
last_execution_time = datetime.strptime(last_execution_time_str, "%Y-%m-%d %H:%M:%S") if last_execution_time_str else None
container_stop_time = datetime.strptime(container_stop_time_str, "%Y-%m-%d %H:%M:%S") if container_stop_time_str else None
if is_within_time_range(current_time):
# 检查容器停止时间限制
if container_stop_time and (current_time - container_stop_time).total_seconds() >= 3600:
logger.info(f"容器已停止超过1小时,尝试启动容器。")
if manage_container_status(current_time):
# 如果容器启动成功,脚本退出
return
# 等待30秒后再执行文件检查
video_files = find_video_files(folder_path)
if not video_files:
logger.info(f"在文件夹 {folder_path} 中没有找到视频文件。")
else:
check_and_manage_files(video_files, current_time)
# 更新状态文件,不论容器是否启动成功
write_status_file(current_time_str, current_time_str)
else:
# 在扫描时间段内检查5分钟限制
if last_execution_time and (current_time - last_execution_time).total_seconds() < 300:
logger.info(f"脚本在5分钟内已经执行过,直接退出。")
return
# 执行文件检查和管理操作
video_files = find_video_files(folder_path)
if not video_files:
logger.info(f"在文件夹 {folder_path} 中没有找到视频文件。")
else:
check_and_manage_files(video_files, current_time)
# 更新状态文件
write_status_file(current_time_str, container_stop_time_str)
else:
# 扫描时间段之外,始终执行容器状态管理
if manage_container_status(current_time):
# 如果容器运行正常,脚本退出
return
# 更新状态文件,仅记录执行时间,不更新容器停止时间
write_status_file(current_time_str, container_stop_time_str)
if __name__ == "__main__":
main()
正文完