实用脚本能批量打包吗?

wen 实用脚本 11

本文目录导读:

实用脚本能批量打包吗?

  1. 批量压缩文件/文件夹
  2. 批量打包成可执行文件(PyInstaller)
  3. 批量打包Docker镜像
  4. 批量打包成单一压缩包(带目录结构)
  5. 跨平台通用脚本(使用7-Zip)
  6. 参数化批量打包脚本
  7. 实用建议

是的,实用脚本完全可以实现批量打包功能,具体取决于你需要的“打包”类型(压缩文件、打包代码、打包容器等)和应用场景,以下是几种常见的批量打包脚本方案及实现示例:

批量压缩文件/文件夹

Python脚本(使用zipfile)

import os
import zipfile
from pathlib import Path
def batch_zip(source_dir, output_dir, file_extensions=None):
    """
    批量压缩指定目录下的文件夹或文件
    :param source_dir: 源目录
    :param output_dir: 输出目录
    :param file_extensions: 文件扩展名列表,如['.txt', '.py'],None表示压缩所有文件夹
    """
    os.makedirs(output_dir, exist_ok=True)
    for item in os.listdir(source_dir):
        item_path = os.path.join(source_dir, item)
        # 如果是文件夹,直接压缩
        if os.path.isdir(item_path):
            zip_name = f"{item}.zip"
            zip_path = os.path.join(output_dir, zip_name)
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
                for root, dirs, files in os.walk(item_path):
                    for file in files:
                        file_path = os.path.join(root, file)
                        arcname = os.path.relpath(file_path, item_path)
                        zf.write(file_path, arcname)
            print(f"已压缩: {item} -> {zip_name}")
        # 如果是文件且匹配扩展名
        elif file_extensions and os.path.isfile(item_path):
            ext = Path(item).suffix
            if ext in file_extensions:
                zip_name = f"{Path(item).stem}.zip"
                zip_path = os.path.join(output_dir, zip_name)
                with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
                    zf.write(item_path, item)
                print(f"已压缩: {item} -> {zip_name}")
# 使用示例
batch_zip(r"C:\my_documents", r"C:\backups", file_extensions=[".pdf", ".docx"])

Shell脚本(Linux/Mac,使用tar或zip)

#!/bin/bash
# batch_pack.sh
SOURCE_DIR="/path/to/source"
OUTPUT_DIR="/path/to/output"
mkdir -p "$OUTPUT_DIR"
# 遍历所有子目录并打包
for dir in "$SOURCE_DIR"/*/; do
    dir_name=$(basename "$dir")
    tar -czf "$OUTPUT_DIR/${dir_name}.tar.gz" -C "$SOURCE_DIR" "$dir_name"
    echo "已打包: $dir_name"
done
# 或者使用zip
# zip -r "$OUTPUT_DIR/${dir_name}.zip" "$dir"

批量打包成可执行文件(PyInstaller)

# batch_pyinstaller.py
import os
import subprocess
def batch_pack_python_scripts(scripts_dir):
    """
    批量将Python脚本打包为exe
    """
    for file in os.listdir(scripts_dir):
        if file.endswith('.py'):
            script_path = os.path.join(scripts_dir, file)
            output_name = os.path.splitext(file)[0]
            cmd = [
                'pyinstaller',
                '--onefile',
                '--name', output_name,
                '--distpath', os.path.join(scripts_dir, 'dist'),
                script_path
            ]
            print(f"正在打包: {file}")
            subprocess.run(cmd, check=True)
            print(f"完成: {output_name}.exe")
if __name__ == "__main__":
    batch_pack_python_scripts(r"C:\my_scripts")

批量打包Docker镜像

#!/bin/bash
# batch_docker_build.sh
DOCKERFILES_DIR="./dockerfiles"
OUTPUT_TAG_PREFIX="myapp"
for dockerfile in "$DOCKERFILES_DIR"/*.Dockerfile; do
    # 提取服务名
    service_name=$(basename "$dockerfile" .Dockerfile)
    docker build -t "${OUTPUT_TAG_PREFIX}/${service_name}:latest" \
                 -f "$dockerfile" \
                 .
    echo "已构建镜像: ${OUTPUT_TAG_PREFIX}/${service_name}:latest"
done

批量打包成单一压缩包(带目录结构)

# consolidate_pack.py
import os
import tarfile
from datetime import datetime
def consolidated_pack(source_dir, output_file, file_patterns=None):
    """
    将多个文件或文件夹打包到同一个压缩包中
    """
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    if not output_file:
        output_file = f"backup_{timestamp}.tar.gz"
    with tarfile.open(output_file, "w:gz") as tar:
        for root, dirs, files in os.walk(source_dir):
            for file in files:
                # 如果指定了文件模式,则进行过滤
                if file_patterns:
                    if not any(file.endswith(pattern) for pattern in file_patterns):
                        continue
                file_path = os.path.join(root, file)
                tar.add(file_path, arcname=os.path.relpath(file_path, source_dir))
    print(f"已打包到: {output_file}")
# 使用示例:只打包 .log 和 .txt 文件
consolidated_pack("/var/log", "logs_backup.tar.gz", [".log", ".txt"])

跨平台通用脚本(使用7-Zip)

# batch_7zip.ps1 (Windows PowerShell)
$sourceDir = "C:\Projects"
$outputDir = "C:\Backups"
# 创建输出目录
New-Item -ItemType Directory -Force -Path $outputDir
# 批量压缩每个文件夹
Get-ChildItem -Path $sourceDir -Directory | ForAll-Object {
    $zipName = "$($_.Name).7z"
    $zipPath = Join-Path $outputDir $zipName
    & "C:\Program Files\7-Zip\7z.exe" a -t7z $zipPath $_.FullName
    Write-Host "已压缩: $($_.Name) -> $zipName"
}

参数化批量打包脚本

# flexible_batch_pack.py
import argparse
import os
import zipfile
import tarfile
def main():
    parser = argparse.ArgumentParser(description='批量打包工具')
    parser.add_argument('source', help='源目录')
    parser.add_argument('output', help='输出目录')
    parser.add_argument('--format', choices=['zip', 'tar.gz', 'tar.bz2'], default='zip',
                        help='打包格式')
    parser.add_argument('--type', choices=['dirs', 'files', 'all'], default='all',
                        help='打包对象类型')
    parser.add_argument('--pattern', help='文件匹配模式,如 *.txt')
    args = parser.parse_args()
    os.makedirs(args.output, exist_ok=True)
    for item in os.listdir(args.source):
        item_path = os.path.join(args.source, item)
        # 判断是否匹配类型
        if args.type == 'dirs' and not os.path.isdir(item_path):
            continue
        if args.type == 'files' and not os.path.isfile(item_path):
            continue
        if args.pattern:
            import fnmatch
            if not fnmatch.fnmatch(item, args.pattern):
                continue
        # 压缩
        base_name = os.path.splitext(item)[0]
        output_path = os.path.join(args.output, f"{base_name}.{args.format}")
        if args.format == 'zip':
            with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zf:
                if os.path.isdir(item_path):
                    for root, dirs, files in os.walk(item_path):
                        for file in files:
                            file_path = os.path.join(root, file)
                            arcname = os.path.relpath(file_path, item_path)
                            zf.write(file_path, arcname)
                else:
                    zf.write(item_path, item)
        elif args.format in ['tar.gz', 'tar.bz2']:
            mode = 'w:gz' if args.format == 'tar.gz' else 'w:bz2'
            with tarfile.open(output_path, mode) as tar:
                tar.add(item_path, arcname=item)
        print(f"已打包: {item} -> {os.path.basename(output_path)}")
if __name__ == "__main__":
    main()

实用建议

  1. 选择工具

    • 简单批量:Shell/Batch脚本
    • 复杂逻辑:Python(最灵活)
    • 跨平台:Python + 7-Zip
  2. 性能优化

    • 使用 multiprocessing 并行打包
    • 对大文件设置内存缓冲
  3. 错误处理

    • 添加 try/exceptset -e
    • 记录失败文件列表
  4. 日志记录

    import logging
    logging.basicConfig(filename='pack.log', level=logging.INFO)

你可以根据自己的操作系统、文件类型和打包需求选择合适的方案,如果需要特定场景的脚本,欢迎提供更多细节!

抱歉,评论功能暂时关闭!