Skip to content

Commit b54cbb9

Browse files
committed
adding example on cli module
1 parent 93d180c commit b54cbb9

2 files changed

Lines changed: 158 additions & 0 deletions

File tree

‎example/cli-module/main.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
"""
5+
Main cli-program, to start it all up by reading command line
6+
options and arguments and the executing whats to be executed.
7+
8+
See usage.py for details how to use program.
9+
>>> import usage
10+
>>> help(usage)
11+
12+
or
13+
14+
$ pydoc usage
15+
16+
"""
17+
18+
import sys
19+
from usage import Usage
20+
21+
22+
def main():
23+
"""Main function where it all starts."""
24+
usage = Usage()
25+
usage.parse_options()
26+
27+
print("Default options:")
28+
print(usage.default_options)
29+
30+
print("Active options:")
31+
print(usage.options)
32+
print()
33+
34+
sys.exit()
35+
36+
37+
if __name__ == "__main__":
38+
main()

‎example/cli-module/usage.py‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
"""
5+
Usage and parsing options.
6+
7+
Exit status:
8+
0 EXIT_SUCCESS success
9+
1 EXIT_USAGE failed parsing cli options
10+
2 EXIT_FAILED Execution error
11+
"""
12+
13+
import os
14+
import sys
15+
import getopt
16+
17+
18+
#
19+
# Add basics about this program
20+
#
21+
PROGRAM = os.path.basename(sys.argv[0])
22+
AUTHOR = "Your Name"
23+
EMAIL = "your@email"
24+
VERSION = "v1.0.0 (2017-06-15)"
25+
26+
MSG_USAGE = """{program} - short description on what this command does.
27+
By {author} ({email}), version {version}.
28+
29+
Usage:
30+
{program} [options] <command>
31+
32+
Options:
33+
-h, --help Display this help message.
34+
-v, --version Print version and exit.
35+
--silent Decrease verbose output.
36+
--verbose Increase verbose output.
37+
""".format(
38+
program=PROGRAM,
39+
author=AUTHOR,
40+
email=EMAIL,
41+
version=VERSION
42+
)
43+
44+
MSG_VERSION = "{version}".format(version=VERSION)
45+
46+
MSG_HELP = "Use {program} --help to get usage.".format(program=PROGRAM)
47+
48+
49+
#
50+
# Global default settings affecting behaviour of script in several places
51+
#
52+
EXIT_SUCCESS = 0
53+
EXIT_USAGE = 1
54+
EXIT_FAILED = 2
55+
56+
57+
class Usage(object):
58+
"""
59+
Parse CLI options and return as dict.
60+
61+
Present usage and version information.
62+
"""
63+
64+
# pylint: disable=R0201
65+
66+
default_options = {
67+
"verbose": False,
68+
"silent": False,
69+
}
70+
71+
options = {}
72+
73+
def __init__(self):
74+
"""Initiate."""
75+
self.options = self.default_options.copy()
76+
77+
def print_usage(self, exit_status=0):
78+
"""Print usage information about the script and exit."""
79+
print(MSG_USAGE)
80+
sys.exit(exit_status)
81+
82+
def print_version(self):
83+
"""Print version information and exit."""
84+
print(MSG_VERSION)
85+
sys.exit()
86+
87+
def parse_options(self, argv=None):
88+
"""
89+
Parse all command line options and arguments.
90+
91+
Return them as a dictionary.
92+
"""
93+
argv = argv if argv is not None else sys.argv[1:]
94+
try:
95+
opts, _ = getopt.getopt(argv, "hv", [
96+
"help",
97+
"version",
98+
"silent",
99+
"verbose"
100+
])
101+
102+
for opt, _ in opts:
103+
if opt in ("-h", "--help"):
104+
self.print_usage()
105+
106+
elif opt in ("-v", "--version"):
107+
self.print_version()
108+
109+
elif opt in "--silent":
110+
self.options["silent"] = True
111+
112+
elif opt in "--verbose":
113+
self.options["verbose"] = True
114+
115+
except getopt.GetoptError as err:
116+
print(err)
117+
print(MSG_HELP)
118+
sys.exit(EXIT_USAGE)
119+
120+
return self.options

0 commit comments

Comments
 (0)