argparse action or type for comma-separated list

The simplest solution is to consider your argument as a string and split.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--myarg", type=str)
args = parser.parse_args()
if args.myarg is not None:
    args.myarg = [s.strip() for s in args.myarg.split(",")]
print(args)

Result:

$ ./toto.py --myarg=abcd,e,fg
Namespace(myarg=['abcd', 'e', 'fg'])
$ ./toto.py --myarg="abcd, e, fg"
Namespace(myarg=['abcd', 'e', 'fg'])

Leave a Comment

tech