Created
November 26, 2018 07:58
-
-
Save shiumachi/e4490f5887091a71787f47a063509718 to your computer and use it in GitHub Desktop.
argparse sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import argparse | |
import sys | |
class MyArgParse(object): | |
def __init__(self): | |
pass | |
def sum(self): | |
print "sum sum" | |
def set_option(self): | |
self.parser = argparse.ArgumentParser(description='test argparse') | |
self.parser.add_argument('integers', metavar='N', type=int, nargs='+', help='test option 1') | |
self.parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='test option2') | |
self.parser.add_argument('-a', help='no options. one extra argument is required. it simply conains integer') | |
self.parser.add_argument('-b', action='store_const', const=100, help="action='store_const'. no argument is needed. b will contain const(100 is set)") | |
self.parser.add_argument('-c', action='store_true', help="action='store_true'. no argument is needed. c will be set to true. if you need to set false, use store_false") | |
self.parser.add_argument('-d', action='append', help="action='append'. put all arguments into list. you can specify this option any times") | |
self.parser.add_argument('-e', action='append_const', const='10', help="action='append_const' put const value into list every time you specify this option. you can use '-eee' like format to set this option multiple times") | |
self.parser.add_argument('--version', action='version', version='%(prog)s 1.0', help="action='version'. just show version and exit") | |
self.parser.add_argument('-f', nargs=3, help="nargs=3. you should give 3 arguments for this option") | |
self.parser.add_argument('-g', nargs='?', const='201', default='200', help="nargs='?'. if no optional options are specified, default value will be set. if only -g is specifed, const value will be set") | |
self.parser.add_argument('-i', nargs='*', help="nargs=*. all arguments are put into a list") | |
self.parser.add_argument('foo', type=int, help="type=int.") | |
def print_args(self): | |
args = self.parser.parse_args() | |
print sys.argv | |
print args | |
print args.accumulate(args.integers) | |
print("a = " + str(args.a)) | |
print("b = " + str(args.b)) | |
print("c = " + str(args.c)) | |
print("d = " + str(args.d)) | |
print("e = " + str(args.e)) | |
print("f = " + str(args.f)) | |
print("g = " + str(args.g)) | |
print("i = " + str(args.i)) | |
print("foo + 10 = " + str(args.foo + 10)) | |
if __name__=='__main__': | |
myap = MyArgParse() | |
myap.set_option() | |
myap.print_args() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment