Python - Command Line Arguments with Python - Two different ways

Here is an example with arguments:
__author__ = 'Almir Mustafic'


import sys, getopt


def main():
    print("main program")
    # simple_example()
    getopt_example_with_arguments(sys.argv[1:])


# Run the following example: python arguments_example.py 123 456 789
def simple_example():
    print 'Number of arguments:', len(sys.argv), 'arguments.'
    print 'Argument List:', str(sys.argv)

    if len(sys.argv) >= 2:
        print('Argument 1 is: {0}' .format(sys.argv[1]))

    print("")

    for index, ar in enumerate(sys.argv):
        print("Argument {0} is: {1}" .format(index, ar))


# usage: arguments_example.py -i <inputfile> -o <outputfile>
# usage: arguments_example.py --ifile in.txt --ofile out.txt
def getopt_example_with_arguments(my_argv):
    print("getopt example...........")

    inputfile = ''
    outputfile = ''

    try:
        opts, args = getopt.getopt(my_argv, "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        print 'test.py -i <inputfile> -o <outputfile>'
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print 'test.py -i <inputfile> -o <outputfile>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg

    print 'Input file is "', inputfile
    print 'Output file is "', outputfile


################################################

if __name__ == "__main__": main()




No comments:

Post a Comment