""" TreeAndDir.py ------------- Captures a full directory listing (dir /s) and a file tree (tree /F /A) of the current working directory and saves both outputs to text files. Requirements: Python 3.8+, Windows OS (uses cmd.exe built-ins) """ import os import subprocess import sys import time from pathlib import Path def run_command(args: list[str], output_path: Path, label: str) -> bool: """ Execute a shell command and stream its output directly to a file. Args: args: Command + arguments list passed to subprocess. output_path: Destination file for stdout/stderr. label: Human-readable name shown in progress messages. Returns: True on success, False if the process exits with a non-zero code. """ print(f"Running '{' '.join(args[2:])}'...") start = time.perf_counter() try: with output_path.open("w", encoding="utf-8", errors="replace") as fh: result = subprocess.run( args, stdout=fh, stderr=subprocess.STDOUT, check=False, # handle non-zero exits ourselves ) except OSError as exc: print(f" ERROR: could not write to {output_path}: {exc}", file=sys.stderr) return False elapsed = time.perf_counter() - start if result.returncode != 0: print( f" WARNING: '{label}' exited with code {result.returncode}.", file=sys.stderr, ) size_kb = output_path.stat().st_size / 1024 print(f" Saved to {output_path} ({size_kb:.1f} KB, {elapsed:.2f}s)") return result.returncode == 0 def main() -> int: cwd = Path.cwd() dir_output = cwd / "DirOutput.txt" tree_output = cwd / "TreeOutput.txt" results = [ run_command(["cmd", "/c", "dir", "/s"], dir_output, "dir /s"), run_command(["cmd", "/c", "tree", "/F", "/A"], tree_output, "tree /F /A"), ] print("\nDone." if all(results) else "\nCompleted with warnings.") # Only pause when run interactively (not piped / redirected) if sys.stdin.isatty(): input("\nPress Enter to exit...") return 0 if all(results) else 1 if __name__ == "__main__": sys.exit(main())