Example code - parsing command line options

From 22118
Revision as of 11:12, 21 February 2026 by WikiSysop (talk | contribs) (Created page with "This is one selfmade way of dealing with command line parameters for your program. <pre> #!/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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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

#!/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)