Search code examples
pythonargparse

python argparse option string not complete but value is assigned


Argparse doesn't seem to check for entire string of option to assign the value. Is this a bug or intended one? What are the use cases for this if this is intended?

Run the following program using python3 test.py -test "testing"

import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-testurl', dest='testurl')
    args = parser.parse_args()
    print(args)

Output is

Namespace(testurl='testing')


Solution

  • We can use double dash (--) in options and make allow_abbrev=False in parser to force the exact argument to be parsed [reference: argument parser documentation]:

    import argparse
    if __name__ == '__main__':
        parser = argparse.ArgumentParser(allow_abbrev=False)
        parser.add_argument('--testurl', dest='testurl')
        args = parser.parse_args()
        print(args)
    

    Output:

    > python3 df_reg.py --test "testing" 
    usage: df_reg.py [-h] [--testurl TESTURL]
    df_reg.py: error: unrecognized arguments: --test testing
    
    > python3 df_reg.py --testurl "testing"
    Namespace(testurl='testing')
    

    References: