Repository navigation
Expand file tree
/
Copy pathmynameis2.py
More file actions
executable file
·195 lines (134 loc) · 4.25 KB
/
Copy pathmynameis2.py
File metadata and controls
executable file
·195 lines (134 loc) · 4.25 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Example to show how command-line options can be handled by a script.
"""
import sys
import os
from datetime import datetime
import getopt
#
# Add some stuff about this script
#
PROGRAM = os.path.basename(sys.argv[0])
AUTHOR = "Mikael Roos"
VERSION = "1.1.0"
USAGE = """{program} - Print my name. By {author} ({email}), version {version}.
Usage:
{program} [options] name
Options:
-h, --help Display this help message.
-v, --version Print version and exit.
-s, --silent Do not display any details or statistics
about the execution.
-d <number>, --drums=<number> Make a drum sound when writing the name.
-r <number>, --repeat=<number> Print the name several times.
-o <filename>, --output=<filename> Save output to file.
name Your name.
""".format(program=PROGRAM, author=AUTHOR, email=EMAIL, version=VERSION)
MSG_VERSION = "{program} version {version}.".format(program=PROGRAM, version=VERSION)
MSG_USAGE = "Use {program} --help to get usage.\n".format(program=PROGRAM)
#
# Global default settings affecting behaviour of script in several places
#
REPEAT = 0
DRUM = 0
SILENT = False
VERBOSE = True
NAME = ""
OUTPUT = None
EXIT_SUCCESS = 0
EXIT_USAGE = 1
EXIT_FAILED = 2
def printUsage(exitStatus):
"""
Print usage information about the script and exit.
"""
print(USAGE)
sys.exit(exitStatus)
def printVersion():
"""
Print version information and exit.
"""
print(MSG_VERSION)
sys.exit(EXIT_SUCCESS)
def printMyName():
"""
Print the name.
"""
msg = "My name is "
if DRUM:
msg += NAME[0:1] * DRUM
msg += NAME
msg += NAME * REPEAT
msg += "!"
print(msg)
if OUTPUT:
if VERBOSE:
print("Saving output to file: ", OUTPUT)
with open(OUTPUT, "w") as f:
f.write(msg + "\n")
def parseOptions():
"""
Merge default options with incoming options and arguments and return them as a dictionary.
"""
# Switch through all options
try:
global DRUM, REPEAT, VERBOSE, OUTPUT, NAME
opts, args = getopt.getopt(sys.argv[1:], "hvsd:r:o:", [
"help",
"version",
"silent",
"drum=",
"repeat=",
"output="
])
for opt, arg in opts:
if opt in ("-h", "--help"):
printUsage(EXIT_SUCCESS)
elif opt in ("-v", "--version"):
printVersion()
elif opt in ("-s", "--silent"):
VERBOSE = False
elif opt in ("-d", "--drum"):
if not arg.isnumeric():
assert False, "-d, --drum: {arg} is not a numeric value".format(arg=arg)
DRUM = int(arg)
if VERBOSE:
print("Setting DRUM to ", DRUM)
elif opt in ("-r", "--repeat"):
if not arg.isnumeric():
assert False, "-r, --repeat: {arg} is not a numeric value".format(arg=arg)
REPEAT = int(arg)
if VERBOSE:
print("Setting REPEAT to ", REPEAT)
elif opt in ("-o", "--output"):
OUTPUT = arg
if VERBOSE:
print("Setting OUTPUT to ", OUTPUT)
else:
assert False, "Unhandled option"
if len(args) != 1:
assert False, "Missing name as argument"
# The name passed as a required argument
NAME = args[0]
except Exception as err:
print(err)
print(MSG_USAGE)
# Prints the callstack, good for debugging, comment out for production
# traceback.print_exception(Exception, err, None)
sys.exit(EXIT_USAGE)
def main():
"""
Main function to carry out the work.
"""
startTime = datetime.now()
parseOptions()
printMyName()
timediff = datetime.now()-startTime
if VERBOSE:
sys.stderr.write("Script executed in {}.{} seconds\n".format(timediff.seconds, timediff.microseconds))
sys.exit(EXIT_SUCCESS)
if __name__ == "__main__":
main()