0

I am using getops for args management and for some reason my -s variable is not working. My code is below, as well as the output I am getting

try:
  opts, args = getopt.getopt(sys.argv[1:], "hadsp:v", ["help", "all", "display", "single=", "present="])#, "search="])
except getopt.GetoptError as err:
  print(err)
  print "Exiting now, no options entered"
  help()
  sys.exit(2)

if len(opts) == 0:
  print "No options passed"
  help()

print opts
print args

for o, a in opts:
  if o in ("-h", "--help"):
    help()
  elif o in ("-p", "--present"):
    search(a)
  elif o in ("-a", "--all"):
    all_install()
  elif o in ("-s", "--single"):
    if a == '':
      print "crap"
      sys.exit(2)
    single_install(a)
  elif o in ("-d", "--display"):
    display()
  else:
    print "Exiting now, unknown option"
    help()
    sys.exit(2)

And the output is

[('-s', '')]
['test']
crap

when I run the program:

python file.py -s test

Not sure why this is happening, thanks for any help

user2455869
  • 151
  • 1
  • 13

1 Answers1

1
import argparse

argParser = argparse.ArgumentParser()
argParser.add_argument(
        '-p', '--present', dest='present', help='write help here for this parameter')

args = argParser.parse_args()

if args.present:
    search(a)

Sample code to use argparse, which is easier to manage and use -h (or) --help is inbuilt option for argparse

If you would like to use getopt, please refer to documentation for parsing the options

https://docs.python.org/2/library/getopt.html

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
be_good_do_good
  • 4,311
  • 3
  • 28
  • 42