#!/usr/bin/env python3 """Utility for doing simple FX conversions.""" from __future__ import annotations import plistlib import subprocess import sys def read_cache() -> dict[str, float]: return plistlib.loads( subprocess.check_output( ("defaults", "export", "com.apple.calculateframework", "-"), ) )["currencyCache"] def main() -> None: if len(sys.argv) == 1 or "--help" in sys.argv[1:] or "-h" in sys.argv[1:]: print(f"{sys.argv[0]} [to_currency=USD]") print(__doc__) sys.exit(0) value_raw, *args = sys.argv[1:] value_raw = value_raw.replace(",", "").replace(" ", "") if not value_raw.isnumeric(): value = float("".join(x for x in value_raw if x.isnumeric()) or "1") from_currency = "".join(x for x in value_raw if not x.isnumeric()) else: value = float(value_raw) from_currency, *args = args if args: to_currency, *args = args else: to_currency = "USD" cache = read_cache() fx_rate = cache[to_currency] / cache[from_currency] print(f"{value * fx_rate:{',.2f' if value != 1.0 else ''}}") if __name__ == "__main__": main()