blob: 699151fa52b52cab85da0afc6c003e3d215e4087 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
#!/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]} <value> <from_currency> [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()
|