让我们有一个以数字为输入的程序。不过,可以指定基座。未指定时,该数字以小数点为基数。
# 10 in decimal
./get_num.py 10
# 10 in octal
./get_num.py -o 12
# 10 in binary
./get_num.py -b 1010我想使用模块,但无法找到实现这一结果的方法。我知道有一个选项可以使用互斥群,但这并不适合,因为这样就需要始终指定基。
模型代码:
#!/usr/bin/env python3
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('base')
parser.add_argument('-o')
parser.add_argument('-b')
args = parser.parse_args()
if args.o: print('octal', args.o)
if args.b: print('binary', args.b)
else: print('decimal', args.base)发布于 2017-10-14 01:01:59
我觉得这就是你想要的。在默认情况下,不需要指定互斥组中的基= false。
import argparse
parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group()
group.add_argument('-b', action='store_true')
group.add_argument('-o', action='store_true')
parser.add_argument('num', help='number')
args=parser.parse_args()
base=10 # default base
if args.b:
base=2
elif args.o:
base=8
# add other bases as required
print(int(args.num, base=base))产出;
run get_num.py -b 1010
10
run get_num.py -o 12
10
run get_num.py 10
10
run get_num.py -b -o 12
usage: PROG [-h] [-b | -o] num
PROG: error: argument -o: not allowed with argument -b
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2发布于 2017-10-14 01:29:15
使用dest、action='store_const'和const选项到argparse中的add_argument,您可以这样做:
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
parser.add_argument('value', help='Value')
group.set_defaults(base=10)
group.add_argument('-b', dest='base', action='store_const', const=2,
help="Use base 2")
group.add_argument('-o', dest='base', action='store_const', const=8,
help="Use base 8")
args = parser.parse_args()
print("Value {value}, base {base}".format(value=args.value, base=args.base))取得了以下结果:
$ python base.py 100
Value 100, base 10
$ python base.py 100 -b
Value 100, base 2
$ python base.py 100 -b2
usage: base.py [-h] [-b | -o] value
base.py: error: argument -b: ignored explicit argument '2'
$ python base.py 100 -o
Value 100, base 8
$ python base.py 100 -o -b
usage: base.py [-h] [-b | -o] value
base.py: error: argument -b: not allowed with argument -o您还可以考虑使用一个整数值(默认为10)的--base选项。对我来说,这使你的程序更清晰、更简单:
parser = argparse.ArgumentParser()
parser.add_argument('value', help='Value')
parser.add_argument('-B', '--base', type=int, default=10,
help="Base to use")https://stackoverflow.com/questions/46739682
复制相似问题