Passing a List to Python From Command Line

后端 未结 4 1569
面向向阳花
面向向阳花 2020-11-29 05:09

I would like to make my python script run from the command line when supplies with some arguments. However, one of the arguments should be a list of options specific to one

4条回答
  •  半阙折子戏
    2020-11-29 05:54

    Yes, argparse is your best bet, and if you want to provide a list of values to one of your named arguments, it looks like this (the nargs parameter is the key to this):

    >>> import argparse
    >>> arg_parser = argparse.ArgumentParser()
    >>> arg_parser.add_argument('--details',
                                nargs='*',
                                type=str,
                                default=[],
                                help='a list of the details')
    
    # your args on the command line like this example
    >>> the_args = arg_parser.parse_args("--details 'name' 'title' 'address'".split())
    >>> print the_args.details
    ["'name'", "'title'", "'address'"])
    

提交回复
热议问题