Please explain an example from the standard python getopt documentation.

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() 

In particular, where can I get the usage() function? Why are the sys.exit() and sys.exit(2) parameters so different? What is the role of the verbose variable? What does the assert False ... command do assert False ... ?

    1 answer 1

    usage is simply a function that lists the arguments and a brief description of how to use them. Written by yourself (yes, you can take your name).

    The -v often used for two things — either output a version of the application, or "enhance output." This example is used for the second. The bottom line is that if verbose == False , then the program displays few messages, and if True , more. Convenient for debugging. Some console utilities also use parameters like -vv and -vvv for even more detailed output to the log. Again, everything is implemented by the programmer in the code, because only he knows which messages are important and which are less.

    The parameters used in this example are how often they are used in console applications in Linux (and not only), that for many they do not even raise any questions about their names and assignments :)

    sys.exit() is the end of the program. Ahead of time. And the argument in brackets is what the operating system returns. The fact is that in Linux (and Windows too) it is assumed that if a program exits normally, then it should return zero. Otherwise, some number. (and this number in the range from 0 to 127, if memory serves me). By this code, other programs that run this can judge the results of its work. What does it mean any non-zero number is the choice of the creator of the program and this is described in the documentation (but not always).

    And the most recent is assert False, "unhandled option" - but this is already a bit of a strange code, but absolutely legal. assert takes two arguments - a boolean expression and a string. If the expression is True, then nothing is done. If False (as in this case), then the specified string is displayed to the user (for example, to the terminal) and the program is terminated. Usually, assert (which should be read like this "states that the following expression is true in a given line, and if this is not the case, output the specified message and be signed") where you need to check the correctness of the program's behavior. in short, assert can be translated into code somewhere like that (implementations can be very different)

     def assert(cond, message): if not cond: print message sys.exit(1) 

    but only the compiler and the library are aware of this function and can do more - display the infrastructure or call the debugger (it all depends on the language and environment).

    • Approached me to understand. Thanks :) And how to determine whether the parameter is required for input, for example, output? By adding a '=' sign - Rado Duoistin
    • And how to determine the required parameter or not? For example, 'output', by adding the character '='? - Rado Duoistin
    • No Optional arguments are not supported. Use another library - KoVadim
    • @KoVadim Why did you find the assert strange? It seems to be a normal stub in case you forgot to do the processing of some option. - zed
    • because assert False . More terrible is just assert True :) I honestly expected something like raise Exception('unhandled option') ; there is no die in python. - KoVadim