Search code examples
pythonargparseoptparse

Using optparse or argparse to process multiple arguments using the same option


I'm trying to write a python script that can echo whatever a user types when running the script

Right now, the code I have is (version_msg and usage_msg don't matter right now)

from optparse import OptionParser 

version_msg = ""
usage_msg = ""
parser = OptionParser(version=version_msg, usage=usage_msg)
parser.add_option("-e", "--echo", action="append", dest="input_lines", default=[])

But if I try to run the script (python options.py -e hello world), it echoes just ['hello']. How would I go about fixing this so it outputs ['hello', 'world']?


Solution

  • A slightly hacky way of doing it:

    from optparse import OptionParser
    
    version_msg = ""
    usage_msg = ""
    parser = OptionParser(version=version_msg, usage=usage_msg)
    parser.add_option("-e", "--echo", action="append", dest="input_lines", default=[])
    
    options, arguments = parser.parse_args()
    
    print(options.input_lines + arguments)
    

    I then run

    python myscript.py -e hello world how are you
    

    Output:

    ['hello', 'world', 'how', 'are', 'you']