Boolean argument for script

后端 未结 3 966
一整个雨季
一整个雨季 2021-02-01 00:03

In Python, I understand how int and str arguments can be added to scripts.

parser=argparse.ArgumentParser(description=\"\"\"Mydescription\"\"\")
parser.add_argum         


        
3条回答
  •  有刺的猬
    2021-02-01 00:54

    import distutils.util
    ARGP.add_argument('--on', '-o', type=distutils.util.strtobool, default='true')
    

    Example calling it:

    $ ./myscript                # argp.on = 1
    $ ./myscript --on=false     # argp.on = 0
    $ ./myscript --on=False     # argp.on = 0
    $ ./myscript --on=0         # argp.on = 0
    $ ./myscript --on=1         # argp.on = 1
    $ ./myscript -o0            # argp.on = 0
    $ ./myscript -o false       # argp.on == 0
    

    i should mention, you can bind the argument to a local wrapper function too, to handle some other exact string matching if you want to support values like "yes" and "no". you can also try interpreting the input as yaml, which can handle yes/no too. i haven't done this in a while though, and i think lately I've suck to mutually exclusive arguments with the same dest value, one --no-option with action='store_false', and one --option with action='store_true'

提交回复
热议问题