Engineering

Python Command Line Args

By July 30, 2022 No Comments

Command line arguments are the string of data and flags that are passed into a python script for execution to change behavior. You leverage the built-in sys module to get access to the sys.argv list.

python example.py my name is david

print('Number of arguments:', len(sys.argv), 'arguments.')
print('Argument List:', str(sys.argv))

Number of arguments: 5

Argument List: [‘example.py’, ‘my’, ‘name’, ‘is’, ‘david’]

The built-in getopt module can help parse command line arguments that use a flag syntax -h, -i abc123, etc.

python example.py -a 1 -b 2 -c 3
import sys, getopt

def main(argv):
   a = ''
   b = ''
   c = ''

   try:
      opts, args = getopt.getopt(argv,"ha:b:c:",["aaa=","bbb=","ccc="])
   except getopt.GetoptError:
      print('example.py -a <a> -b <b> -c <c>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print('example.py -a <a> -b <b> -c <c>')
         sys.exit()
      elif opt in ("-i", "--aaa"):
         a = arg
      elif opt in ("-b", "--bbb"):
         b = arg
      elif opt in ("-c", "--ccc"):
         c = arg
   print('A ' + a)
   print('B ' + b)
   print('C ' + c)

if __name__ == "__main__":
   main(sys.argv[1:])

The sys.argv[1:] code above actually returns a slice from the list of [‘example.py’, ‘1’, ‘2’, ‘3’], thus only forwarding on [‘1′,’2′,’3’]