hi i've been trying to parse the argument using getopt

i need to have it to be able to handle

argv[0] logfile
(i ment to take the following argument after argv and put it in variable - like listed in the usage part)

but i coudnt get it to work properly...
it calls the usage() if i supply an argument after argv[0]

#!/usr/bin/env python

import getopt,sys
import string

#print sys.argv[1:]
def usage():
    print "usage: ",sys.argv[0]," [-u ip-address] | [-s] [-t] logfile"
    print "-u: username"
    print "-s: summary"
    print "-t: cpu time"
    sys.exit(2)
def main():
    try:    
        #u:st: [there is a parameter following -u and -t options,option -s without parameter]
        opts, args = getopt.getopt(sys.argv[1:], "u:st:")
    except getopt.GetoptError:
        #print help information and exit:
        sys.stdout = sys.stderr
        usage()
    user = 0
    summary = 0
    total = 0
    for o, a in opts:
        if o == "-u":
            #print "user: true"
            user = 1
        if o in ("-s"):    
            #print "summary: true"
            summary = 1
        if o in ("-t"):
            #print "total: true"
            total = 1
    if user and summary:
        sys.stdout = sys.stderr
        print "-u and -s are mutually exclusive"
        sys.exit(2)
    if user == 0 and summary == 0 and total == 0:
        sys.stdout = sys.stderr
        usage()

if __name__ == '__main__':
    main()

please help..im a newbie

thanks in advance...

The way your code works, if you just type progname data.log
, this statement will be active if user == 0 and summary == 0 and total == 0: and you will see the usage() output.

So your program is behaving properly, even if it's not what you want. If you want to get the argument (not an -option) you should look in args, which is a list of the arguments. In the example above you would have args = . Perhaps that is what you want.

This article has been dead for over six months. Start a new discussion instead.