sandeep jain
sandeep jain

Reputation: 11

How to get a compulsory argument without option using getopt in Python?

So I have this program which takes zero or more optional arguments. There is however one compulsory argument (region) which should be passed always. I've a 'if' condition which sets the compulsory arg to the sys.argv[1] when no options are detected and to sys.argv[-1] (the last arg) when one or more options are detected. The problem is it'll not throw an error when options are passed and the compulsory arg is not passed. Is there a way in getopt that accepts a compulsory arg which does not have any option.

./prog.py region -> works fine

./prog.py -c 4 -s 2 region -> works fine

./prog.py -c 4 -s 2 -> sets region to 2 which is not desired, should throw an error instead

Any suggestion is appreciated.

Upvotes: 1

Views: 1415

Answers (1)

Joe
Joe

Reputation: 31110

getopt returns the unparsed arguments when you call it; check for the compulsory argument in that list, rather than the original args that you provided.

import getopt

for cmdline in ['region', '-c 4 -s 2 region', '-c 4 -s 2']:
  print('Given: %s' % cmdline)
  args = cmdline.split()
  optlist, args = getopt.getopt(args, 'c:s:')
  print(' Args: %s' % optlist)
  print(' Remaining: %s' % args)

gives:

Given: region
 Args: []
 Remaining: ['region']
Given: -c 4 -s 2 region
 Args: [('-c', '4'), ('-s', '2')]
 Remaining: ['region']
Given: -c 4 -s 2
 Args: [('-c', '4'), ('-s', '2')]
 Remaining: []

Upvotes: 2

Related Questions