如何在argparse中的命令后捕获和使用数据?

时间:2016-02-25 12:00:43

标签: python argparse

您好我在argparse文档中一无所知。我希望能够捕获和使用用户给出的遵循给定命令的数据。

例如:

python func.py -type mult -data 2 3 1
6 (2*3*1)

python func.py -type add -data 2 5 1
8 (2+5+1)

你会怎么做这个功能?

2 个答案:

答案 0 :(得分:0)

import argparse

parser = argparse.ArgumentParser(
    description="Math equations",
    formatter_class=argparse.RawTextHelpFormatter
)

parser.add_argument("-type", choices=("mult", "add", "div", "sub"), required=True)
parser.add_argument("-data", nargs='+', type=int, required=True) # '+' for nargs means one or more.  If you want it to be limited to three, just change it to 3.

args = vars(parser.parse_args())
print(args)

python func.py -type mult -data 2 3 1

{'data': [2, 3, 1], 'type': 'mult'}

python func.py -type mul -data 2 3 1

usage: func.py [-h] -type {mult,add,div,sub} -data DATA [DATA ...]
test.py: error: argument -type: invalid choice: 'mul' (choose from 'mult', 'add', 'div', 'sub')

python func.py -h

usage: test.py [-h] -type {mult,add,div,sub} -data DATA [DATA ...]

Math equations

optional arguments:
  -h, --help            show this help message and exit
  -type {mult,add,div,sub}
  -data DATA [DATA ...]

python func.py -data 2 3 1

usage: func.py [-h] -type {mult,add,div,sub} -data DATA [DATA ...]
test.py: error: argument -type is required

答案 1 :(得分:0)

每一次开始都很艰难。作为一个例子(尽管从长远来看,提供解决方案可能不会对您有所帮助),但代码可能如下所示:

import argparse
import numpy as np

# map the -type inputs to a function and a symbol for printing
TYPE_MAP = {
    'mult': {'func': np.prod, 'symbol': '*'},
    'add': {'func': np.sum, 'symbol': '+'}
}

# parse the args
def _parse_args():
    parser = argparse.ArgumentParser(description='Foo')
    parser.add_argument('-type', choices=TYPE_MAP.keys(), type=str,
                        help='specify type of operation that we want to do')  # we accept 1 known string as input
    parser.add_argument('-data', nargs='+', type=float,
                        help='specify numbers to process')  # we accept a space separated list of inputs
    return parser.parse_args()

if __name__ == '__main__':
    args = _parse_args()

    # make stuff in args easily accessable
    symbol = TYPE_MAP[args.type]['symbol']
    func = TYPE_MAP[args.type]['func']
    data = args.data

    # compute stuff
    result = func(data)
    details = '(' + symbol.join([str(number) for number in data]) + ')'

    # print stuff
    print result, details

为了从中学习,您可以尝试向此方法添加更多功能或添加其他参数。也许你可以添加一个抑制打印细节的参数。