List of arguments with argparse

后端 未结 2 794
时光说笑
时光说笑 2021-01-18 10:42

I\'m trying to pass a list of arguments with argparse but the only way that I\'ve found involves rewriting the option for each argument that I want to pass:

What I c

2条回答
  •  逝去的感伤
    2021-01-18 11:28

    Being aware, you asked for argparse solution, I would like to present alternative solution using package docopt

    Install it first:

    $ pip install docopt
    

    Write the code:

    """Usage:
        main.py -a ...
    """
    
    if __name__ == "__main__":
        from docopt import docopt
        resargs = docopt(__doc__)
        print resargs
    

    Run it to show usage instrucitons:

    $ python main.py
    Usage:
        main.py -a ...
    

    Call it with your parameters:

    $ python main.py -a AA BB CC
    {'-a': True,
     '': ['AA', 'BB', 'CC']}
    

    Btw. if you do not need the -a option, you shall directly allow passing the arguments. It makes usage simpler to the user.

提交回复
热议问题