Search code examples
pythonparsingcommand-line-argumentsgetoptpython-2.4

How to read multiple command line parameters with same flag in Python?


A user should be able to call the Python script like this:

python myScript.py -i inputFile.txt -k string1 -k string2 -k string3 -o outputFile.txt

or like this:

python myScript.py -i inputFile.txt -o outputFile.txt -k string1 -k string2

Inside the script, I want to end up reading in the "-i" parameter, the "-o" parameter, and put all the "-k" parameters (variable amount) into an ordered list.

I want to do this in a clean way (I know I can write this myself from scratch, but I would rather use an already-built library/module).

I must use Python 2.4.3 and would like to use getopt (if not something similar). I am not allowed to download argparse either.


Solution

  • Given the constraints in my question (Python 2.4.3, no installation of argparse), I made it work as follows:

    from optparse import OptionParser
    
    parser = OptionParser()
    parser.add_option('-f', action='append')
    parser.add_option('-i', action='store')
    parser.add_option('-o', action='store')
    (options, args) = parser.parse_args()
    print options
    print args
    

    Given this command line:

    python test_argparse.py -f hi -f bye -i input1 -i input2 -o output1 -o output2
    

    I got:

    {'i': 'input2', 'o': 'output2', 'f': ['hi', 'bye']}
    []