Basic information for python

less than 1 minute read

import sys 
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-a", help="parameter a")
parser.add_argument("-b", help="parameter b")
parser.add_argument("-c", help="parameter c")
args = parser.parse_args()

argc = len(sys.argv)
print(argc)

if args.a:
    print "a : " + args.a
if args.b:
    print "b : " + args.b
if args.c:
    print "c : " + args.c
# python test2.py -aaaaa -bbbbbbb
3
a : aaaa
b : bbbbbb

# python test2.py -a aaaa -b bbbbbb
5
a : aaaa
b : bbbbbb

# python test2.py -f aaaa -b bbbbbb
usage: test2.py [-h] [-a A] [-b B] [-c C]
test2.py: error: unrecognized arguments: -f aaaa

Checking parameters

#----------------------------------------------
# Check & Run
#----------------------------------------------
if __name__ == '__main__':
    argc = len(sys.argv)
    print("Starting...(Argc:" + str(argc) + ")")

    try:
        if argc >= 5:
            gmtype = sys.argv[1]
            grtype = sys.argv[2]
            gfname = sys.argv[3]
            gsgrep = sys.argv[4]
            print("Filename: [" + gfname + "]")
            view_message(gmtype, grtype, gfname, gsgrep)
        elif argc >= 4:
            gmtype = sys.argv[1]
            grtype = sys.argv[2]
            gfname = sys.argv[3]
            gsgrep = ""
            print("Filename: [" + gfname + "]")
            view_message(gmtype, grtype, gfname, gsgrep)
        else:
            usage()
            sys.exit(0)
    except KeyboardInterrupt, IOError:
        print (" ----------------- The End -----------------")
        sys.exit(1)

Tags:

Categories:

Updated:

Leave a comment