Search code examples
pythongetopt

Cannot handle parameters with getopt python


In order to offer options to my python script, I want to introduce some parameters. I found that the better way to do this in python is with getopt, but once I run my script it doesn't do anything. Please help me!!!. This is my code:

def main(argv):
     try:
            opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output='])
    except getopt.GetoptError:
            usage()
            sys.exit(2)
            file = None
            outfile = None
    for opt, arg in opts:
            if opt in ('-h', '--help'):
                    usage()
                    sys.exit(2)
            elif opt in ('-i', '--input'):
                    file = arg
            elif opt in ('-o', '--output'):
                    outfile = arg
            elif opt == '-t':
                    maininfo(file,outfile)
            else:
                    usage()
                    sys.exit(2)

if __name__ =='__main__':
    main(sys.argv[1:])

Solution

  • I suggest adding more logging. Not only will this help you out now, it'll help out whoever uses your script in future.

    def main(argv):
        filename = None
        outfile = None
        call_maininfo = False
        try:
            opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output='])
            if not opts:
                print 'No options supplied'
                usage()
        except getopt.GetoptError, e:
            print e
            usage()
            sys.exit(2)
        for opt, arg in opts:
            if opt in ('-h', '--help'):
                usage()
                sys.exit(2)
            elif opt in ('-i', '--input'):
                filename = arg
            elif opt in ('-o', '--output'):
                outfile = arg
            elif opt == '-t':
                call_maininfo = True
            else:
                usage()
                sys.exit(2)
    
        print 'Processed options [{0}] and found filename [{1}] and outfile [{2}]'.format(
                ', '.join(argv),
                filename,
                outfile,
                )
    
        if call_maininfo:
            print 'Calling maininfo()'
            maininfo(filename, outfile)
    

    I also moved the call to maininfo() out of the loop as you could supply -t before the filenames!