Answer the question
In order to leave comments, you need to log in
How does the getopt module from the Python standard library work?
Please explain an example from the standard python getopt documentation.
In particular, where do you get the usage() function from? Why such different parameters sys.exit()
and ? What role does the variable play ? What does the team dosys.exit(2)
verbose
assert False ...?
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
if __name__ == "__main__":
main()
Answer the question
In order to leave comments, you need to log in
Just a tip: before you dive into getopt, take a look at Click , which is a high-level wrapper around argparse/optparse (a high-level alternative to getopt) that is designed to solve many of the problems that your code solves manually, as well as many of the problems that you will soon encounter when developing console applications.
This function should print something to the console about how to properly call your script and with what parameters.
This should signal to the OS or calling script whether the process exited normally (return code == 0, not specified by default) or exited with an error (return code > 0).
In many Unix utilities, the verbose mode means outputting more detailed information about the progress of the work; without it, the process can work out (normally, without errors) in general silently without any output. Your implementation is up to you.
It should be placed at a point to which, logically, the interpreter should not reach in any case. In this case, IMHO, its use is unreasonable, it would be more correct to simply write something like "unhandled option" to the console and exit by sys.exit(n)
where n > 0
.
Use argparse.
And these questions have nothing to do with getopt, nothing at all.
usage() and verbose are just do-it-yourself things that can be written by anyone.
https://docs.python.org/3/library/sys.html#sys.exit
https://docs.python.org/3/reference/simple_stmts.h...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question