Hongmu Notes
Home Language Notes python cooperates with winrar to specify folders and package in batches
Language Notes python

python cooperates with winrar to specify folders and package in batches

python cooperates with winrar to specify folders and package in batches

I recently put this together myself – it works pretty well!
Back up the data.

So you don't end up losing it next time.

#!/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()

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

Import " requests" could not be resolved from source

Import " requests" could not be resolved from source Language Notes python

This error occurred when using Pylance, a Python language server. Among them, " Import " requests" could not be resolved from source" This error message indicates that the requests module is referenced in your code, but Pylance cannot find the location of the module from the source. The possible reason is that you don't have an …
👁 1771
Reinstall Python and requests libraries

Reinstall Python and requests libraries Language Notes python

If you meet " Import " requests" could not be resolved from source" You can try reinstalling Python and requests libraries. First, you need to uninstall the current Python and requests libraries. On Windows systems, you can use the command prompt …
👁 439
WARNING: Skipping requests as it is not installed.

WARNING: Skipping requests as it is not installed. Language Notes python

This error message indicates that your Python environment lacks the requests library, and this library is called in your code, so Python cannot execute your code normally. The solution to this problem is to install the requests library. You can use the pip command on the command line to install: pip install requests If you are using Python3, you can use the pip3 command …
👁 2100
Python reported an error. What is the reason? AttributeError: partially initialized module ' openai'  has no attribute ' Completion' (most likely due to a circular import)

Python reported an error. What is the reason? AttributeError: partially initialized module ' openai' has no attribute ' Completion' (most likely due to a circular import) Language Notes python

This error prompt indicates that there is a problem when importing the openai module and the specific Completion attribute, which is probably caused by circular import. The reason for this error may be that two or more modules in your code are imported from each other, forming a circular dependency. For example, module A imports module B, and module B imports module A.. Cyclic import will cause the module not to initialize correctly when loading, thus …
👁 656
How does python package and run on Windows?

How does python package and run on Windows? Language Notes python

The most common way to package and run Python programs on Windows is to use PyInstaller. PyInstaller is a free and cross-platform Python application packaging tool, which can package Python code and its dependent libraries into an independent executable file, making it possible to run Python programs on systems without Python interpreters installed. The following is to make …
👁 300
What programming software is good for python development?

What programming software is good for python development? Language Notes python

There are many programming softwares developed by Python. The following are some commonly used Python integrated development environments (IDE) and editors: PyCharmPyCharm is an integrated development environment developed by JetBrains, which is specially designed for Python developers. PyCharm is powerful and provides a series of advanced functions such as code completion, debugging, version control, code refactoring, etc., which can help developers improve their work …
👁 175

Recommended reading

(Adaptive Mobile Version) Responsive Eco-Friendly Tech Website Template – 0994

(Adaptive Mobile Version) Responsive Eco-Friendly Tech Website Template – 0994 Practical Collection pbootcms Template

A responsive, eco-friendly PbootCMS website template compatible with both PC and WAP devices. Its modern, sustainable design makes it ideal for environmental technology companies to showcase their equipment products, technical solutions, and green initiatives. This template helps environmental enterprises build a strong online brand presence and attract customers. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 45
Responsive infant and children's clothing website template – 0983

Responsive infant and children's clothing website template – 0983 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the infant and children's clothing industry. Its stylish and playful design is perfect for showcasing children's apparel products, infant and toddler garments, brand identity, and new product launches. It helps children's clothing brands attract parent consumers online and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Questions for EyouCMS...
👁 44
(Adaptive Mobile Version) Swimming Pool Equipment – PBootCMS Website Template; Download Website Source Code for Swimming Pool Water Treatment Systems – 0438

(Adaptive Mobile Version) Swimming Pool Equipment – PBootCMS Website Template; Download Website Source Code for Swimming Pool Water Treatment Systems – 0438 Practical Collection pbootcms Template

An adaptive mobile-friendly swimming pool equipment and water treatment system website template (PbootCMS). The clean and professional design is ideal for showcasing swimming pool equipment, water treatment systems, and project cases. It helps swimming pool equipment companies showcase their products online and attract clients from hotels and sports venues. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.c...
👁 63
Responsive Vehicle Tire Rim Website Template (Bilingual) 0392

Responsive Vehicle Tire Rim Website Template (Bilingual) 0392 Practical Collection Yiyou template

An eYouCMS responsive bilingual website template designed for the vehicle tire and wheel rim industry. Its professional, international design style effectively showcases tire and wheel rim products, technical specifications, export advantages, and brand identity. Multi-language support enables businesses to promote their brands across global markets. Template Demo | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS...
👁 65
What should I do if the output file name displayed in Windows shows garbled characters?

What should I do if the output file name displayed in Windows shows garbled characters? Summary of pitfalls

My code: $filesss = glob('./pic/*.jpg'); print_r($filesss); When running this code on a Windows environment, the output file name appears as garbled text. The reason for this issue is that PHP on Windows defaults to using the system's native encoding when processing file names, which can cause file names containing Chinese characters or other non-ASCII characters to be displayed as garbled text during output. Solution...
👁 216
(PC + WAP) High-end and sophisticated interior design company website template – 0995

(PC + WAP) High-end and sophisticated interior design company website template – 0995 Practical Collection pbootcms Template

A premium and sophisticated PbootCMS website template designed for renovation and decoration companies, compatible with both PC and WAP devices. Its modern, luxurious design is ideal for high-end residential and commercial renovation firms to showcase their design portfolios and brand strength. This template helps renovation companies attract high-quality clients online. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 59