Search code examples
pythongetopt

Python getopt recognizing options as arguments


I'm trying to parse some options when running a Python script.

def main(argv):
    try:
        opts, args = getopt.getopt(argv,"a:p:i:r",["algo=", "population=", "iterations=", "random"])
    except getopt.GetoptError:
        printUsage()
        sys.exit(1)
    print(args, opts)
    #Afterwards, I parse the options
    #...

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

However, when I run this

python tsp.py cities.txt -p 4

The print(args, opts) yields this.

(['cities.txt', '-p', '4'], [])

Why is it parsing options as arguments?


Solution

  • getopt requires that all - options come first. -p 4 instead came after a non-dash option.

    python tsp.py -p 4 cities.txt will be parsed correctly.

    You may want to switch to using the argparse library instead; it is far more flexible and can parse optional command line switches in any location, as it also handles required arguments explicitly.