Last active
December 22, 2019 00:11
-
-
Save wpm/bfeba03746bd494092266a0691455b4a to your computer and use it in GitHub Desktop.
Use Celery workers to copy a directory of files in parallel, with error tracking and a progress bar.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import shutil | |
from pathlib import Path | |
from typing import Iterable, Tuple, Optional | |
import click | |
from celery import Celery | |
from celery.utils.log import get_task_logger | |
from tqdm import tqdm | |
app = Celery("copy", broker="pyamqp://guest@localhost//", backend="rpc://") | |
logger = get_task_logger(__name__) | |
@app.task(name="copy_files") | |
def copy_files(destination: str, filename: str) -> Tuple[str, int, Optional[str]]: | |
def copy_without_overwrite(): | |
if destination_filename.exists(): | |
raise IOError(f"{destination_filename} exists") | |
shutil.copy(filename, destination_filename) | |
destination = Path(destination) | |
filename = Path(filename) | |
destination_filename = destination / filename.name | |
error = None | |
try: | |
copy_without_overwrite() | |
except Exception as e: | |
error = str(e) | |
logger.error(e) | |
return str(destination_filename), filename.stat().st_size, error | |
@click.command("copy-directory") | |
@click.argument("source", type=click.Path(exists=True, file_okay=False)) | |
@click.argument("destination", type=click.Path(file_okay=False)) | |
@click.option("--chunk-size", default=50, show_default=True, help="Number of files to copy per worker") | |
def copy_directory(source: str, destination: str, chunk_size: int): | |
""" | |
Copy a directory of files. | |
This uses Celery workers to do the copy in parallel, displays a progress bar that updates according to file size, | |
and tracks copy errors for individual files. | |
This will not overwrite files. If the file already exists in the destination directory, an error will be logged. | |
Too start the Celery worker run the following command in this directory. | |
\b | |
celery -A celery_copy_directory worker | |
""" | |
def files() -> Iterable[Path]: | |
return (filename for filename in source.iterdir() if filename.is_file()) | |
def total_size() -> int: | |
return sum(filename.stat().st_size for filename in files()) | |
source, destination = Path(source).absolute(), Path(destination).absolute() | |
Path(destination).mkdir(parents=True, exist_ok=True) | |
result = copy_files.chunks([(str(destination), str(filename)) for filename in files()], chunk_size)() | |
errors = [] | |
with tqdm(total=total_size()) as progress: | |
def message_callback(message): | |
if message["status"] == "SUCCESS": | |
for filename, size, error in message["result"]: | |
if error is None: | |
progress.set_description(filename) | |
progress.update(size) | |
else: | |
errors.append(error) | |
result.get(on_message=message_callback) | |
if errors: | |
print("The following files were not copied:") | |
print("\n".join(errors)) | |
if __name__ == "__main__": | |
copy_directory() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment