python argparse模块解析命令行选项简单使用

argparse模块的解析命令行选项简单使用

util.py

#!/usr/bin/env python
# coding=utf-8

import argparse

parser = argparse.ArgumentParser(prog="myprogram ",description="a test of argparse")


parser.add_argument("-a",type=int,dest="start",choices={1,2,3},help="start number")
parser.add_argument("-b",type=int,dest="end",help="end point")
parser.add_argument("-s","--sum",dest="data",required=True,type=int,nargs="*",help="numbers to add")
parser.add_argument("-o",required=True,dest="fw",help="output file")

def cal_sum(a,b):
    s = 0
    for i in range(a,b):
        s += i
    return s

if __name__=="__main__":
    args = parser.parse_args()
    print args
    print vars(args)
    data = args.data
    print sum(data)
    res = str(sum(data))
    with open(args.fw,'wb') as fw:
        fw.write(res)

看看效果:

>:~/$ python util.py -s 1 2 3 -o output.txt
Namespace(data=[1, 2, 3], end=None, fw='output.txt', start=None)
{'start': None, 'fw': 'output.txt', 'end': None, 'data': [1, 2, 3]}
6
jkmiao@jkmiao-ipin:~/workplace/mygithub/leetcodex$ more output.txt 
6

 

你可能感兴趣的:(python argparse模块解析命令行选项简单使用)