[ Team LiB ] Previous Section Next Section

8.4 The getopt Module

The getopt module helps parse the command-line options and arguments passed to a Python program, available in sys.argv. The getopt module distinguishes arguments proper from options: options start with '-' (or '--' for long-form options). The first non-option argument terminates option parsing (similar to most Unix commands, and differently from GNU and Windows commands). Module getopt supplies a single function, also called getopt.

getopt

getopt(args,options,long_options=[  ])

Parses command-line options. args is usually sys.argv[1:]. options is a string: each character is an option letter, followed by ':' if the option takes a parameter. long_options is a list of strings, each a long-option name, without the leading '--', followed by '=' if the option takes a parameter.

When getopt encounters an error, it raises GetoptError, an exception class supplied by the getopt module. Otherwise, getopt returns a pair (opts,args_proper), where opts is a list of pairs of the form (option,parameter) in the same order in which options are found in args. Each option is a string that starts with a single hyphen for a short-form option or two hyphens for a long-form one; each parameter is also a string (an empty string for options that don't take parameters). args_proper is the list of program argument strings that are left after removing the options.

    [ Team LiB ] Previous Section Next Section