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 my name is david

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

Number of arguments: 5

Argument List: [‘’, ‘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 -a 1 -b 2 -c 3
import sys, getopt

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

      opts, args = getopt.getopt(argv,"ha:b:c:",["aaa=","bbb=","ccc="])
   except getopt.GetoptError:
      print(' -a <a> -b <b> -c <c>')
   for opt, arg in opts:
      if opt == '-h':
         print(' -a <a> -b <b> -c <c>')
      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__":

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