Commandline parsing with getoptFebruary 03. 2012
Wirbel's implementation of getoptgetopt is a well known library for parsing command lines. It can handle short options, GNU-style long options, options with optional arguments and many other details. Wirbel has it's own implementation of getopt, which offers a modern API that makes use of Wirbel's functional programming features. It will take the programmer's burden of doing everything right and conforming to standards:
How to use getoptDefining the optionsThe first step for using getopt in your application is to define a table describing all options your programm understands. You need list of six-tuples: Definitions for getopt
options = [ ( 'v', "verbose", `no_argument, `verbose, [], null ), ( 'V', "version", `no_argument, null, [], lambda w,x,y,z: print_version() ), ( 'h', "help", `no_argument, null, [], lambda w,x,y,z: print_usage() ), ( 'o', "output", `required_argument, null, [], set_output_file ), ( null, "debug", `optional_argument, null, [], null ), ( 'c', null, `no_argument, `dont_compile, [`optimize], null ), ( 'O', "optimize", `no_argument, `optimize, [`dont_compile], null ), ] These are the columns:
Calling getoptgetopt takes to argument: the list of actual command line arguments (without argv[0]) and your option table. It will return a list of all seen flags and a list of all non-option arguments. If a syntax error in the commandline is detected then an exception of type getopt will be raised. Its reason-text which will explain the error to the user. getopt_demo.w
try:
seen_flags, arguments = getopt(argv[1:], options)
except getopt:
print(reason)
exit(1)
Handler functions Option handler function might either takeimmediate action and execute the option, or store values for later execution in global variables. The following example function is called whenever the option -o or --output is seen: handler function
def set_output_file(opt, opt_arg, seen_flags, arguments):
print("Ouputfile (Option %s) is %s" % opt % opt_arg)
if `verbose in seen_flags:
print("Verbose output...")
print("Non-option arguments: %s" % arguments)
If you handler function does not take all four parameters you can help yourself with the lambda construct as seen in the upper example. The follo function print_version does not take any parameter:
def print_version():
print("Getopt demo 1.0.17, Copyright Mathias Kettner")
exit(1)
It is entered in the option table as lambda w,x,y,z: print_version(). |
| |||||||||||||||||||||