Apr 19, 2015

QNAP/Linux - Python Programming 03 (Command-Line Arguments)

Arguments of C console application are defined in array "argv", in which the count of arguments is "args". Python supports more flexible method to write console applications with Unix-like "option -" and "long option: --".
python -h (or --help)

The getopt module parses command-line options and arguments.
getopt.getopt(args, options[, long_options])

  • args: The argument list to be parsed, i.e. sys.argv[1:]. argv[0] is the program name.
  • options: Define each option character followed by a colon (:). E.g. "h:i:o:".
  • long_options: Define the optional parameter for long options represented as a list of strings, such as  ["help=", "version="]for --help and --version. The equal sign ('=') is needed. To accept only long options, options should be an empty string.
For example, the following image shows all arguments tried on the program "argv.py".

Error test in the second command
Source code: https://github.com/ilearnblogger/pyp/blob/master/argv.py
Source code explained as followings

  • Line 1: Import getopt module to parse various arguments easily.
  • Line 3-7: Define a function() to show error messages passed by the caller.
  • Line 9, 28: Define the C-like main() function as the program's entry point. The entry point of Python program is denoted by "if __name__ == "__main__": main(sys.argv[1:])". sys.argv[1:] means that arguments start from the second position since the first position argv[0]  is the .py program file name.
  • Line 11-15: try-catch statements for parsing arguments with getopt.
  • Line 12: Get return value into optsargs, "opts, args = getopt.getopt(argv, "hvrwf:", ["help","version","file="])" means "-h -v -r -w -f" are short options and "--help --version --file" are long options, in which "-f" and "--file" must follow a string as the file name. "-r -w" do not support long options.
  • Line 17-25: "for opt, arg in opts: " the for-statement block extracts each options into (opt, arg) like (attribute, value). For example, "-f ff" becomes ("-f", "ff") so that "if-elseif" is applied to write codes for each matched option. 


Alternative module for argument parser: argparse. It is more complex, learn it while you need advanced features, such as solving conflicting arguments.

No comments :

Post a Comment