Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
optparser replacement for getopt
01-23-2010, 03:46 PM
Post: #1
optparser replacement for getopt
Code:
import optparse;

#Coded by codecaine aka Jerome Scott II

parser = optparse.OptionParser();
#add argument options as you can see with this first one -n and --name can be use to name the name as a type string
parser.add_option("-n", "--name", dest="name",type="string");

#add argument options -a or --age can be use as the age argument you can unlimited arguments for that type and the type is int. The type section is optional
parser.add_option("-a", "--age", dest="age", type="int");

I made a post showing getopts before but this method is newer and recommended to use.


#Here is optional but recommended setting default values for arguments not set by the user
parser.set_defaults(name="", age=0);

#make a usage message if the user not using the program correct it will display
parser.set_usage("python opttest.py -n -name -a --age");

#checking if the user enter a name if not display the usage message
opts, args = parser.parse_args();
if opts.name == "":
    print("You must enter a name argument for this program using the -n or --name");
    print(parser.get_usage());
else:
    #display results
    print(opts.name + " " + str(opts.age));
Visit this user's website Find all posts by this user
Quote this message in a reply
01-24-2010, 10:13 PM
Post: #2
RE: optparser replacement for getopt
Very good. I like the way of adding options to parser.

There's a fine line between genius and insanity. I have erased this line.
Oscar Levant
There's a fine line between an administrator and black hat hacker. I have erased this line.
Dr DEBCOL
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: