Files

56 lines
2.2 KiB
Python
Executable File

#!/usr/bin/env python3
# speedconv - speed converter (km/h, mph, m/s, knots)
# Usage: speedconv VALUE [FROM] [--to TO]
# FROM defaults to km/h. With no --to, prints a table in all units.
# Example: speedconv 100 km/h | speedconv 60 mph --to m/s
import argparse, sys
# base unit: m/s
UNITS = {"m/s": 1.0, "km/h": 1 / 3.6, "mph": 0.44704, "knot": 0.514444,
"kn": 0.514444, "ft/s": 0.3048, "c": 299792458.0}
ALIASES = {"kph": "km/h", "kmh": "km/h", "knots": "knot", "kt": "knot",
"fps": "ft/s", "ms": "m/s", "lightspeed": "c"}
def norm(u):
u = u.strip()
return ALIASES.get(u.lower(), ALIASES.get(u, u))
def selftest():
assert abs(100 * UNITS["km/h"] / UNITS["mph"] - 62.137119) < 1e-6
assert abs(60 * UNITS["mph"] / UNITS["m/s"] - 26.8224) < 1e-9
assert abs(1 * UNITS["knot"] / UNITS["km/h"] - 1.8519984) < 1e-9
assert abs(10 * UNITS["m/s"] / UNITS["km/h"] - 36) < 1e-9
print("speedconv selftest: ok (100km/h=62.14mph, 60mph=26.82m/s, 1kt=1.852km/h)")
return 0
def main():
p = argparse.ArgumentParser(prog="speedconv",
description="Speed converter (km/h, mph, m/s, knots, ft/s).")
p.add_argument("value", nargs="?", type=float, help="speed value")
p.add_argument("from_unit", nargs="?", default="km/h", help="unit of VALUE (default km/h)")
p.add_argument("--to", help="convert to this unit only")
p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
a = p.parse_args()
if a.selftest:
return selftest()
if a.value is None:
p.error("VALUE is required")
fu = norm(a.from_unit)
if fu not in UNITS:
print(f"speedconv: unknown unit {a.from_unit!r} (km/h, mph, m/s, knot, ft/s)", file=sys.stderr)
return 2
ms = a.value * UNITS[fu]
if a.to:
tu = norm(a.to)
if tu not in UNITS:
print(f"speedconv: unknown unit {a.to!r}", file=sys.stderr); return 2
print(f"{a.value:g} {fu} = {ms / UNITS[tu]:g} {tu}")
return 0
print(f"{a.value:g} {fu}")
for u in ("km/h", "mph", "m/s", "knot", "ft/s"):
print(f" {u}: {ms / UNITS[u]:g}")
return 0
if __name__ == "__main__":
sys.exit(main())