Comma separated inputs instead of space separated

2019-02-28 12:57发布

I'm using argsparse to recieve inputs from the command line to run my script.

My current input string looks like this:

path> python <\filename\\> -t T1 T2 T3 -f F1 F2

Is there a parameter in argsparse such that instead of separating inputs by space, I can separate them by commas?

In other words:

path> python <\filename\\> -t T1,T2,T3 -f F1,F2

2条回答
倾城 Initia
2楼-- · 2019-02-28 13:15

There is no such feature in argparse.

Alternatives:

  • post-process the args namespace and split/parse the values manually
  • define a custom action and split/parse the values manually
  • define a custom type and split/parse the values manually
  • subclass ArgumentParser and customise ArgumentParser.convert_arg_line_to_args
查看更多
相关推荐>>
3楼-- · 2019-02-28 13:32

You can use module shlex to extract the parameters, then replace commas with spaces, and pass the results to argparse for further processing:

comma_args = shlex.split("-t T1,T2,T3 -f F1,F2")
# ['-t', 'T1,T2,T3', '-f', 'F1,F2']
args = [x.replace(","," ") for x in comma_args]
# ['-t', 'T1 T2 T3', '-f', 'F1 F2']
parse_args(args)
查看更多
登录 后发表回答