-
Notifications
You must be signed in to change notification settings - Fork 0
/
FriendlyArgumentParser.py
70 lines (62 loc) · 2.63 KB
/
FriendlyArgumentParser.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/python3
#
# FriendlyArgumentParser - Argument parser with default help pages
# Copyright (C) 2011-2012 Johannes Bauer
#
# This file is part of pycommon.
#
# pycommon is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; this program is ONLY licensed under
# version 3 of the License, later versions are explicitly excluded.
#
# pycommon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pycommon; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Johannes Bauer <[email protected]>
#
# File UUID c55a0ea0-6dc8-4ceb-a9ff-e54ea8a2ea62
import sys
import argparse
import textwrap
class FriendlyArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
argparse.ArgumentParser.__init__(self, *args, **kwargs)
self.__silent_error = False
def setsilenterror(self, silenterror):
self.__silent_error = silenterror
def error(self, msg):
if self.__silent_error:
raise Exception(msg)
else:
for line in textwrap.wrap("Error: %s" % (msg), subsequent_indent = " "):
print(line, file = sys.stderr)
print(file = sys.stderr)
self.print_help(file = sys.stderr)
sys.exit(1)
def baseint(value, default_base = 10):
if value.lower().startswith("0x"):
return int(value, 16)
elif value.lower().startswith("0b"):
return int(value, 2)
elif value.lower().startswith("0o"):
return int(value, 8)
elif value.lower().startswith("0b"):
return int(value, 2)
else:
return int(value, default_base)
if __name__ == "__main__":
parser = FriendlyArgumentParser(description = "Simple example application.")
parser.add_argument("-d", "--dbfile", metavar = "filename", type = str, default = "mydb.sqlite", help = "Specifies database file to use. Defaults to %(default)s.")
parser.add_argument("-f", "--force", action = "store_true", help = "Do not ask for confirmation")
parser.add_argument("-x", metavar = "hexint", type = baseint, default = "0x100", help = "Defaults to %(default)s.")
parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increases verbosity. Can be specified multiple times to increase.")
parser.add_argument("qids", metavar = "qid", type = int, nargs = "+", help = "Question ID(s) of the question(s) to be edited")
args = parser.parse_args(sys.argv[1:])
print(args)