getopt

How to use getopt

Note to myself : Always forgetting how to use getopt.

Easy simply use a list of options in the REPL console instead of sys.argv[1:]

: getopt.getopt('-a 1 -b b -c copt'.split(),'a:b:c:')[0]                                                                                                              
: [('-a', '1'), ('-b', 'b'), ('-c', 'copt')]

what about long options :

: getopt.getopt('-a 1 -b b --c copt'.split(),'a:b:',['c='])[0]                                                                                                        
: [('-a', '1'), ('-b', 'b'), ('--c', 'copt')]

check also : Parse cmdline opts as obj attributes

Parse cmdline opts as obj attributes

check also: How to use getopt

You can use C-style parser getopt, to “convert” command line options to object attributes

import getopt

class Test:

   #you can provide defaults
   def __init__(self,n=None,x=None,s=None):
      self.opts = {}
      self.n = n
      self.x = x
      self.s = s
      self.h = None

      if sys.argv[0] :#parse on init
         self.parse_args(sys.argv[1:])
         if self.h is not None : self.print_help(); exit()

         for o in [ 'n', 'x', 's' ]  :#list the opt that have to have value
            if getattr(self,o) is None : raise Exception("Missing cmd line option : %s" % o)

   def parse_args(self,arguments):
      try:
         for arg,opt in getopt.getopt(arguments,'h:n:x:s:')[0] :
            setattr(self, arg[1:], int(opt))
      except getopt.GetoptError:
         print("wrong args")
         sys.exit(2)

   def print_help(self):
      print("""
Example :
./test.py -n 0 -x 1000 -s 10

Help :
-n minimum
-x maximum
-s step
   """)