53 lines
2.3 KiB
Python
Executable File
53 lines
2.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# randpick - pick a random item from a list or a file
|
|
# Usage: randpick ITEM... | randpick --file FILE [--count N] [--seed N] [--unique]
|
|
# Items may also come from stdin (one per line). --count picks that many.
|
|
import argparse, random, sys
|
|
|
|
def selftest():
|
|
rng = random.Random(3)
|
|
items = ["alpha", "beta", "gamma", "delta"]
|
|
picks = [rng.choice(items) for _ in range(20)]
|
|
assert all(p in items for p in picks)
|
|
assert len(set(picks)) > 1 # not stuck on one item
|
|
assert random.Random(3).choice(items) == random.Random(3).choice(items)
|
|
s = random.Random(9).sample(items, 3)
|
|
assert len(set(s)) == 3
|
|
print("randpick selftest: ok (choice in list, seeded repeatability, sample unique)")
|
|
return 0
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(prog="randpick",
|
|
description="Pick a random item from a list, a file, or stdin.")
|
|
p.add_argument("items", nargs="*", help="items to pick from")
|
|
p.add_argument("--file", "-f", help="file with one item per line")
|
|
p.add_argument("--count", type=int, default=1, help="how many to pick (default 1)")
|
|
p.add_argument("--seed", type=int, help="seed for reproducible picks")
|
|
p.add_argument("--unique", action="store_true", help="pick without replacement")
|
|
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
|
|
a = p.parse_args()
|
|
if a.selftest:
|
|
return selftest()
|
|
items = list(a.items)
|
|
if a.file:
|
|
try:
|
|
items += [l.rstrip("\n") for l in open(a.file) if l.strip()]
|
|
except OSError as e:
|
|
print(f"randpick: {e}", file=sys.stderr); return 2
|
|
if not items and not sys.stdin.isatty():
|
|
items = [l.rstrip("\n") for l in sys.stdin if l.strip()]
|
|
if not items:
|
|
p.error("no items: give ITEMs, --file, or pipe lines on stdin")
|
|
if a.count < 1:
|
|
print("randpick: --count must be >= 1", file=sys.stderr); return 2
|
|
if a.unique and a.count > len(items):
|
|
print(f"randpick: --count {a.count} exceeds {len(items)} items", file=sys.stderr); return 2
|
|
rng = random.Random(a.seed) if a.seed is not None else random.SystemRandom()
|
|
picks = rng.sample(items, a.count) if a.unique else [rng.choice(items) for _ in range(a.count)]
|
|
for pick in picks:
|
|
print(pick)
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|