• 0 Posts
  • 1 Comment
Joined 3 years ago
cake
Cake day: July 2nd, 2023

help-circle
  • This might go beyond what you were asking for, but I’m always more comfortable handling file paths, deletions and errors in Python.

    #!/usr/bin/env python3
    
    import shutil
    from pathlib import Path
    from tempfile import TemporaryDirectory
    
    # Refuse to run without Python's symlink-resistant cleanup.
    if not getattr(shutil.rmtree, "avoids_symlink_attacks", False):
        raise RuntimeError("Symlink-resistant cleanup is unavailable")
    
    with TemporaryDirectory(prefix="test-run-", dir="/tmp") as name:
        tests = Path(name) / "tests"
        tests.mkdir(mode=0o700)
        print(f"Created {str(tests)!r}", flush=True)
    
        try:
            # Put your test code here.
            (tests / "example.txt").write_text(
                "temporary data\n", encoding="utf-8"
            )
        finally:
            print(f"Cleaning {name!r}", flush=True)
    
    # The entire temporary directory has now been removed.