Example code - parsing command line options

From 22118
Jump to navigation Jump to search

This is one selfmade way of dealing with command line parameters for your program.

You should notice the sys.argv list which is a list of arguments to the program. It is always present when you use the standard sys library.
The first element in the list is the name of the program and that is not needed here. There are use-cases for this though.
BTW, argv is short for argument vector, if you were wondering.

You were taught about sys.argv back in course 22116/22166, See the last slides of the powerpoint, but you probably forgot, since you did not use it.

#!/usr/bin/env python3
# This program demonstrates a way to get arguments and options from command line
import sys

# You should use more appropriately named variable names than me.
# I just don't know what your options are.
# In my example two options are just present or not, but the third requires a number to follow.
# By initalising the option to None, you can later tell that you did not get this option.
# If you initialise it to a value instead, then that becomes a default value, ready to use. 
optionA, optionB, optionNumber = None, None, None
filename = None

# By creating a usage function, you can always call that. Makes it easy to be user friendly
def usage(msg=None):
    # Print a message if there was something specific you want to the user. 
    if msg is not None:
        print(msg, "\n")
    print ("Usage: demooption.py [-a] [-b] [-c <integer>] <filename>")
    # Exit the program. We can not progress. Makes logic easier elsewhere.
    sys.exit(1)

# Command line parsing
# This can be done in different ways. This is just simple. Could be a function.
while len(sys.argv) > 1:
    arg = sys.argv.pop(1)
    if arg == '-a':
        optionA = True
    elif arg == '-b':
        optionB = True
    elif arg == '-c':
        try:
            # There are possibility for failure here - no argument, not integer
            optionNumber = int(sys.argv.pop(1))
            if optionNumber < 1:
                raise ValueError
        except:
            usage()
    elif filename is None:
        filename = arg
    else:
        usage()
    
# Working with the options
if filename is None:
    usage("Hey, you need a filename")
else:
    print("Using this file:", filename)
if optionA:
    print("OptionA reporting for duty")    
if optionB:
    print("OptionB is on the scene")    
if optionNumber is not None:
    print("And the number is:", optionNumber)