Bootstrap FreeKB - Python (Scripting) - Command line options flags arguments using sys.argv
Python (Scripting) - Command line options flags arguments using sys.argv

Updated:   |  Python (Scripting) articles

Command line arguments, options and flags can be created using

You can:

  • Pass in arguments (values)
  • Pass in options (also known as key value pairs)
  • Pass in flags

 


In this example, hello and world are command line arguments.

~]# python example.py hello world

 

Let's say you have the following. sys is imported (part of the Python Standard Library included with your Python installation) so that sys.argv can be used

#!/usr/bin/python
import sys
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])

 

  • sys.argv[0] will contain a value of "example.py"
  • sys.argv[1] will contain a value of "hello"
  • sys.argv[2] will contain a value of "world"

 


The following is nearly the bare minimum needed to create command line options and flags.

#!/usr/bin/python
import sys
import getopt

opts, args = getopt.getopt(sys.argv[1:],"e:p:vh",["env=", "platform=", "verbose", "help"])

for opt, arg in opts:
  if opt in ("-e", "--env"):
    env = arg
  elif opt in ("-p", "--platform"):
    platform = arg
  elif opt in ("-v", "--verbose"):
    verbose = True
  elif opt in ("-h", "--help"):
    help = True

 

You can then use the command line options and flags.

print(f"env      = {env}")
print(f"platform = {platform}")
print(f"verbose  = {verbose}")
print(f"help     = {help}")

 

Which should return the following.

~]$ python tes.py --env development --platform aws --verbose 
env      = development
platform = aws
verbose  = True
help     = Type help() for interactive help, or help(object) for help about object.

 

I like to create short_options variable and long_options list

AVOID TROUBLE

Each short option must be followed by the : (colon) character to be interpreted as an option or must not be followed by the : (colon) character to be interpreted as a flag.

Each long option must be followed by the = character to be interpreted as an option or must not be followed by the = character to be interpreted as a flag.

#!/usr/bin/python
import sys
import getopt

short_options = "e:p:vh"
long_options  = ["env=", "platform=", "verbose", "help"]

opts, args = getopt.getopt(sys.argv[1:],short_options,long_options)

for opt, arg in opts:
  if opt in ("-e", "--env"):
    env = arg
  elif opt in ("-p", "--platform"):
    platform = arg
  elif opt in ("-v", "--verbose"):
    verbose = True
  elif opt in ("-h", "--help"):
    help = True

 

The above will return NameError if one of the command line options and flags are not used, so try / except / else is used to deal with NameError.

#!/usr/bin/python
import sys
import getopt

short_options = "e:p:vh"
long_options  = ["env=", "platform=", "verbose", "help"]

try:
  opts, args = getopt.getopt(sys.argv[1:],short_options,long_options)
except getopt.GetoptError:
  print ("An invalid command line option or flag was used")
  sys.exit(1)

for opt, arg in opts:
  if opt in ("-e", "--env"):
    env = arg
  elif opt in ("-p", "--platform"):
    platform = arg
  elif opt in ("-v", "--verbose"):
    verbose = True
  elif opt in ("-h", "--help"):
    help = True

try:
  env
except NameError:
  pass
else:
  print(f"env = {env}")

try:
  platform
except NameError:
  pass
else:
  print(f"platform = {platform}")

try:
  verbose
except NameError:
  pass
else:
  print(f"verbose = {verbose}")

 

itertools, re.sub, range and len can be used to combine short_options and long_options and to then display the command line options and flags that can be used when the -h or --help flag is used.

#!/usr/bin/python3
import sys
import getopt
import itertools
import re

short_options = "e:p:vh"
long_options  = ["env=", "platform=", "verbose", "help"]
options       = list(itertools.chain.from_iterable(zip(re.sub(":", "", short_options),list(map(lambda x: x.replace('=', ''), long_options)))))
odd           = range(1, len(options), 2)

try:
  opts, args = getopt.getopt(sys.argv[1:],short_options,long_options)
except getopt.GetoptError:
  print (f"{datetime} ERROR An invalid command line option or flag was used. The following command line options and flags can be used:")
  for indice in odd:
    print ("  -" + options[indice-1] + " or --" + options[indice])
  sys.exit(1)

for opt, arg in opts:
  if opt in ("-h", "--help"):
     print ("The following options and flags can be used:")
     for indice in odd:
       print ("  -" + options[indice-1] + " or --" + options[indice])
     sys.exit(0)
  elif opt in ("-e", "--env"):
    env = arg
  elif opt in ("-p", "--platform"):
    platform = arg
  elif opt in ("-v", "--verbose"):
    verbose = True

 

Which should return the following.

 ~]$ python test.py --help
The following options and flags can be used:
  -e or --env
  -p or --platform
  -v or --verbose
  -h or --help

 

Or, include a brief description of each option.

#!/usr/bin/python
import sys
import getopt
import itertools
import re

short_options = "e:p:vh"
long_options  = ["env=",           "platform=", "verbose",              "help"]
description   = ["dev stage prod", "local AWS", "print verbose output", "this help menu"]
options       = list(itertools.chain.from_iterable(zip(re.sub(":", "", short_options),list(map(lambda x: x.replace('=', ''), long_options)),description)))
odd           = range(1, len(options), 3)

try:
  opts, args = getopt.getopt(sys.argv[1:],short_options,long_options)
except getopt.GetoptError:
  print (datetime + " ERROR An invalid command line option or flag was used. The following command line options and flags can be used:")
  for indice in odd:
    print ("  -" + options[indice-1] + " or --" + options[indice])
  sys.exit(1)

for opt, arg in opts:
  if opt in ("-h", "--help"):
     print ("The following options and flags can be used:")
     for indice in odd:
       print ("  -" + options[indice-1] + " or --" + options[indice] + " ("+options[indice+1]+")")
     sys.exit(0)
  elif opt in ("-e", "--env"):
    env = arg
  elif opt in ("-p", "--platform"):
    platform = arg
  elif opt in ("-v", "--verbose"):
    verbose = True

 

Which should print the following.

 ~]$ python test.py --help
The following options and flags can be used:
  -e or --env (dev stage prod)
  -p or --platform (local AWS)
  -v or --verbose (print verbose output)
  -h or --help (this help menu)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter cfa347 in the box below so that we can be sure you are a human.