最近折腾出来的,用起来还不错。
备份一下。
免得下次找不到。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import re
import subprocess
import os
import sys
from pathlib import Path
WWW_ROOT = Path(r"D:\phpstudy_pro\WWW")
DATA_JSON = WWW_ROOT / "data.json"
OUTPUT_DIR = Path(r"C:\Users\18102\Desktop\pbootcms源码文件夹")
PASSWORD = "www.4s5.cn"
WINRAR_PATH = r"C:\Program Files\WinRAR\WinRAR.exe"
EXCLUDED = {"aaa0298.com", "aaa1063.com"}
def get_template_name(site_id_str):
if not DATA_JSON.exists():
return None
site_id_int = int(site_id_str)
with open(DATA_JSON, 'r', encoding='utf-8') as f:
data = json.load(f)
for entry in data:
entry_id = int(entry['id']) if isinstance(entry['id'], str) else entry['id']
if entry_id == site_id_int:
name = entry['name']
match = re.match(r'^k\d+[ _-]', name)
if match:
name = name[match.end():]
return name.strip()
return None
def compress_with_winrar(source_dir, zip_path, verbose=False):
if zip_path.exists() and zip_path.stat().st_size > 0:
if verbose:
print(f" ⏭ 压缩包已存在且非空,跳过")
return True
if not os.path.exists(WINRAR_PATH):
print(f"❌ WinRAR 未找到: {WINRAR_PATH}")
return False
# 使用 -afzip 指定 ZIP 格式(比 -t 更兼容)
cmd = [
WINRAR_PATH,
"a",
"-ep1", # 排除源目录前缀
"-r", # 递归
"-afzip", # 指定 ZIP 格式
f"-p{PASSWORD}",
"-ibck", # 后台运行
"-y",
str(zip_path),
str(source_dir) + "\\" # 源目录路径
]
if verbose:
print(f" 执行命令: {' '.join(cmd)}")
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
if verbose:
print(f" 返回码: {result.returncode}")
if result.stdout:
print(f" stdout: {result.stdout.strip()}")
if result.stderr:
print(f" stderr: {result.stderr.strip()}")
if zip_path.exists() and zip_path.stat().st_size > 0:
return True
else:
if verbose:
print(f" ❌ 未生成有效文件")
return False
except Exception as e:
if verbose:
print(f" ❌ 执行压缩失败: {e}")
return False
def main():
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
site_dirs = []
for d in WWW_ROOT.glob("aaa*"):
if not d.is_dir() or d.name in EXCLUDED:
continue
if d.name.startswith("aaa") and d.name.endswith(".com"):
num_part = d.name[3:-4]
if num_part.isdigit() and len(num_part) >= 4:
site_dirs.append(d)
site_dirs.sort(key=lambda x: int(x.name[3:-4]))
if not site_dirs:
print("未找到任何站点")
return
total = len(site_dirs)
print(f"📋 共找到 {total} 个站点(已排除 {EXCLUDED})")
for idx, site_dir in enumerate(site_dirs, 1):
site_id = site_dir.name[3:-4]
template_name = get_template_name(site_id)
if not template_name:
template_name = f"{site_id}_站点"
zip_name = f"{site_id}_{template_name}.zip"
zip_path = OUTPUT_DIR / zip_name
verbose = (idx <= 3)
if zip_path.exists() and zip_path.stat().st_size > 0:
if verbose:
print(f"\n⏭ {zip_name} 已存在,跳过")
continue
print(f"\n📦 [{idx}/{total}] 打包 {site_dir.name} -> {zip_name} ...")
ok = compress_with_winrar(site_dir, zip_path, verbose)
if ok:
print(f" ✅ 打包成功")
else:
print(f" ❌ 打包失败")
if idx == 3:
print("\n✅ 前3个站点处理完成,请检查上述日志。")
input("按 Enter 键继续处理剩余站点...")
print("\n继续处理剩余站点(仅输出简要信息)...\n")
print("\n🎉 所有站点打包完成!")
if __name__ == "__main__":
main()
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END





![表情[aoman]-红穆笔记](https://www.4s5.cn/wp-content/themes/zibll/img/smilies/aoman.gif)



暂无评论内容