argparse

apgparse 获取参数

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 python
# -*- coding: utf-8 -*-
import argparse

def MY_Argparse():
# ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[],
# formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None,
# argument_default=None, conflict_handler='error', add_help=True)
parser = argparse.ArgumentParser(usage="%(prog)s [options]",add_help=False,
# add_argument (name or flags...[, action][, nargs][, const][, default][, type]
# [, choices][, required][, help][, metavar][, dest])
formatter_class=argparse.RawDescriptionHelpFormatter,
description=('''
Please do not mess up this text!
--------------------------------
I have indented it
exactly the way
I want it'''))
other = parser.add_argument_group('Other arguments')
other.add_argument('-h', '--help', action="store_true", help='help of the %(prog)s program')
other.add_argument('--version', action='version', version='%(prog)s 1.0')
# example = parser.add_argument_group('example', 'example description')
# parser.add_argument(
# '-f', '--foo',
# nargs='*',
# metavar='filename',
# required=True,
# default="hahaha",
# dest='foodest',
# type=str,
# help='foo of the %(prog)s program'
# )
#
# optional.add_argument('--file', type=argparse.FileType('w'))
# optional.add_argument('--choices', type=int, choices=range(1, 4))
optional = parser.add_argument_group('optional arguments')

args=parser.parse_args()
args = vars(args)
if args['help']:
parser.print_help()
return args

Args = MY_Argparse()
print Args

例子

1
2
3
python MY_Argparse.py
-----------------------------------
{'help': False}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
python MY_Argparse.py -h
-----------------------------------
usage: MY_Argparse.py [options]

Please do not mess up this text!
--------------------------------
I have indented it
exactly the way
I want it

Other arguments:
-h, --help help of the MY_Argparse.py program
--version show program's version number and exit
{'help': True}
1
2
3
python MY_Argparse.py --version
-----------------------------------
MY_Argparse.py 1.0
打赏
0%