0

I have defined some of the options using optparse for my python script. In my script the user enters command line arguments in any order, but I want to sort in my predefined way. Let's say the user enters the following arguments:

scriptname -g gvalue -n nvalue -s svalue -k kvalue -e evalue

When the user enters the above parameters in any order, I want to sort in the following manner:

-s svalue -g gvalue -k kvalue -n nvalue -e evalue

Ultimately I need the above order at any time.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
user2572165
  • 51
  • 1
  • 4
  • 3
    I don't understand; opt parse will give you the arguments by name, regardless of the original order. – Scott Hunter Jul 11 '14 at 14:03
  • 1
    you use actions different from "store action" in your optparse configuration? (namely "callback") – Emanuele Paolini Jul 11 '14 at 14:03
  • 1
    Why do you need to sort them? You could sort them but it's really unneeded. Also, [argparse](https://docs.python.org/2/howto/argparse.html), optparse is deprecated. – Jess Jul 11 '14 at 14:05
  • 1
    Also see [this post](http://stackoverflow.com/questions/3217673) on why to use `argparse` instead of `optparse`. – Tom Zych Jul 11 '14 at 14:09

2 Answers2

1

There are probably better ways to get what you want. You shouldn't need to do this. But here's the fix:

I'm going to use argparse because optparse is deprecated. This code will show None if the user has not specified a value for that argument

## directory user$ ./argparse_ex.py -s foo -g bar -k quox -n woo -e testing123

import argparse
parser = argparse.ArgumentParser(description='Sorted Arguments')
parser.add_argument('-s', help='I will be printed if the user types --help')
parser.add_argument('-g', help='I will be printed if the user types --help')
parser.add_argument('-k', help='I will be printed if the user types --help')
parser.add_argument('-n', help='I will be printed if the user types --help')
parser.add_argument('-e', help='I will be printed if the user types --help')

args = vars(parser.parse_args())

sorted_args = [args['s'], args['g'], args['k'], args['n'], args['e']]
print sorted_args

## ['foo', 'bar', 'quox', 'woo', 'testing123']

argparse documentation here

Jess
  • 3,097
  • 2
  • 16
  • 42
0

Assuming optparse is defined with commands for each value such as:

parser.add_option("-k", action="store", type="string", dest="kvalue")

and executed as:

(options, args) = parser.parse_args()

Then options.kvalue will contain the relevant user-inputted argument for -k. Then the sequence in order could be generated:

( getattr(options,name) for name in ('svalue', 'gvalue', 'kvalue', 'nvalue', 'evalue') )

Alternatively, string comparisons on the raw argv can achieve the same thing without using optparse.

mdurant
  • 27,272
  • 5
  • 45
  • 74