整套工具跑一遍
下面是组装好的 conv 精简版。运行它,看五组参数各给出什么(结果或退出码):
import argparse
LEN = {"m": 1.0, "km": 1000.0}
class UsageError(Exception):
pass
class P(argparse.ArgumentParser):
def error(self, m):
raise UsageError(m)
def fmt(x):
return ("%.2f" % x).rstrip("0").rstrip(".")
p = P(prog="conv")
sub = p.add_subparsers(dest="cmd")
t = sub.add_parser("temp")
t.add_argument("value", type=float)
t.add_argument("--to", default="f", choices=["f", "k"])
l = sub.add_parser("len")
l.add_argument("value", type=float)
l.add_argument("--to", required=True)
def run(argv):
try:
a = p.parse_args(argv)
except UsageError:
return "e2"
if a.cmd == "temp":
return fmt(a.value * 9 / 5 + 32 if a.to == "f" else a.value + 273.15)
if a.to not in LEN:
return "e3"
return fmt(a.value / LEN[a.to])
cases = (["temp", "37"], ["len", "5000", "--to", "km"], ["temp", "abc"], ["len", "1", "--to", "li"], ["temp", "100", "--to", "k"])
print("/".join(run(c) for c in cases))
全部评论