shuffle.py (1545B)
1 #!/usr/bin/env python3 2 import argparse 3 import random 4 import subprocess 5 import sys 6 from pathlib import Path 7 8 9 def main() -> None: 10 parser = argparse.ArgumentParser(description="picks and plays random albums in mpd") 11 _ = parser.add_argument("file", type=Path) 12 _ = parser.add_argument( 13 "-n", 14 "--number", 15 type=int, 16 help="number of random albums (default: 5)", 17 ) 18 _ = parser.add_argument( 19 "-d", 20 "--depth", 21 type=int, 22 help="minimum path depth to include (default: 0)", 23 ) 24 25 class Arguments(argparse.Namespace): 26 file: Path = Path() 27 number: int = 5 28 depth: int = 2 29 30 args = parser.parse_args(namespace=Arguments()) 31 32 with open(args.file) as f: 33 lines = [line.strip() for line in f if line.strip()] 34 35 if args.depth > 0: 36 lines = [line for line in lines if line.count("/") >= args.depth] 37 38 if not lines: 39 print("file is empty or no lines match depth criteria", file=sys.stderr) 40 sys.exit(1) 41 42 n: int = min(args.number, len(lines)) 43 selected: list[str] = random.sample(lines, n) 44 45 for line in selected: 46 print(f" → {line}") 47 try: 48 result = subprocess.run(["mpc", "add", line], check=True) 49 _ = result 50 except subprocess.CalledProcessError as e: 51 print(f"error adding '{line}': {e}", file=sys.stderr) 52 except OSError: 53 print("mpc not found", file=sys.stderr) 54 sys.exit(1) 55 56 57 if __name__ == "__main__": 58 main()