How to pass an entire list as command line argument in Python?

前端 未结 7 1789
滥情空心
滥情空心 2020-12-02 16:59

I was trying to pass two lists containing integers as arguments to a python code. But sys.argv[i] gets the parameters as a list of string.

Input would

相关标签:
7条回答
  • 2020-12-02 17:57

    Don't reinvent the wheel. Use the argparse module, be explicit and pass in actual lists of parameters

    import argparse
    # defined command line options
    # this also generates --help and error handling
    CLI=argparse.ArgumentParser()
    CLI.add_argument(
      "--lista",  # name on the CLI - drop the `--` for positional/required parameters
      nargs="*",  # 0 or more values expected => creates a list
      type=int,
      default=[1, 2, 3],  # default if nothing is provided
    )
    CLI.add_argument(
      "--listb",
      nargs="*",
      type=float,  # any type/callable can be used here
      default=[],
    )
    
    # parse the command line
    args = CLI.parse_args()
    # access CLI options
    print("lista: %r" % args.lista)
    print("listb: %r" % args.listb)
    

    You can then call it using

    $ python my_app.py --listb 5 6 7 8 --lista  1 2 3 4
    lista: [1, 2, 3, 4]
    listb: [5.0, 6.0, 7.0, 8.0]
    
    0 讨论(0)
提交回复
热议问题