Thursday 15 July 2021

Python argument parser - parse only from console

Can I extract only the parsed arguments from the command line, ignoring all default arguments? If the user passed the default value for an argument, I would like it to appear in the subset as well:

parser = argparse.ArgumentParser()
parser.add_argument("--a",type=str,default='a')
parser.add_argument("--b",type=str,default='b')
parser.add_argument("--c",type=str,default='c')
parser.add_argument("--d",type=str,default='d')
python run.py --a "e" --b "b"

I would like to have

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--a",type=str,default='a')
    parser.add_argument("--b",type=str,default='b')
    parser.add_argument("--c",type=str,default='c')
    parser.add_argument("--d",type=str,default='d')

    from_cli = parse_from_cli(parser) # from_cli = {'a':'e','b':'b'}

The scenario: a parsed arguments dictionary is being loaded from a disk from a previous run, where a new argument dictionary is created during this run. I would like to override the old dictionary only by the flags that were specifically defined by the new user.



from Python argument parser - parse only from console

No comments:

Post a Comment