-1

Possible Duplicate:
How can I get optparse’s OptionParser to ignore invalid arguments?

I want to use optparse to parse my input. How do I get optparse to ignore the options not provided and just append them to args instead? The users of my program are not computer-savvy, and I do not want to explain to them that they need to provide '--' on the command line to get some arguments through.

Community
  • 1
  • 1
Akash
  • 277
  • 2
  • 11
  • can you give an example what exactly you want, because if they don't want to append -- or - to option how they are going to pass or distinguish options? – Anurag Uniyal Nov 16 '11 at 19:19
  • For example. Say my program is calc.py, and it takes something like 'calc.py --add 3 -2' as arguments, optparse gives "no such options: -2" – Akash Nov 16 '11 at 19:26
  • @Akash: Does it also act like this when you set `nargs=2`? – Daenyth Nov 16 '11 at 19:42
  • @Akash See my answers edits; it shows an example of using nargs and default values. – chown Nov 16 '11 at 20:04

1 Answers1

1

Just set default values with default=, then if the arg is not given, the default value will be used:

from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

To add multiple arguments for an option, use nargs=#:

import optparse

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option("-a", "--add", nargs=2, dest="add")
    (options, args) = parser.parse_args()

    first_add = int(options.add[0])
    second_add = int(options.add[1])
    print "%d" % (first_add + second_add)

Results in:

[ 12:05 jon@hozbox ~/SO/python ]$ ./optparse-add-options-not-found-to-args.py --add 1 -2
-1
[ 12:07 jon@hozbox ~/SO/python ]$ ./optparse-add-options-not-found-to-args.py -a -50 -75
-125

http://docs.python.org/library/optparse.html

chown
  • 51,908
  • 16
  • 134
  • 170