Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse action or type for comma-separated list

I want to create a command line flag that can be used as

./prog.py --myarg=abcd,e,fg

and inside the parser have this be turned into ['abcd', 'e', 'fg'] (a tuple would be fine too).

I have done this successfully using action and type, but I feel like one is likely an abuse of the system or missing corner cases, while the other is right. However, I don't know which is which.

With action:

import argparse

class SplitArgs(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values.split(','))


parser = argparse.ArgumentParser()
parser.add_argument('--myarg', action=SplitArgs)
args = parser.parse_args()
print(args.myarg)

Instead with type:

import argparse

def list_str(values):
    return values.split(',')

parser = argparse.ArgumentParser()
parser.add_argument('--myarg', type=list_str)
args = parser.parse_args()
print(args.myarg)
like image 686
Ryan Haining Avatar asked Sep 01 '18 20:09

Ryan Haining


People also ask

How can I pass a list as a command line argument with Argparse?

To pass a list as a command-line argument with Python argparse, we can use the add_argument to add the argument. to call add_argument with the argument flag's short and long forms. We set nargs to '+' to let us take one or more argument for the flag.

What is action in Argparse?

action defines how to handle command-line arguments: store it as a constant, append into a list, store a boolean value etc. There are several built-in actions available, plus it's easy to write a custom one.

What is Nargs Python?

Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value. import argparse parser = argparse. ArgumentParser() parser.

What does Argparse ArgumentParser () do?

ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required .


1 Answers

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)
d = vars(parser.parse_args())
if "myarg" in d.keys():
    d["myarg"] = [s.strip() for s in d["myarg"].split(",")]
print(d)

Result:

$ ./toto.py --myarg=abcd,e,fg
{'myarg': ['abcd', 'e', 'fg']}
$ ./toto.py --myarg="abcd, e, fg"
{'myarg': ['abcd', 'e', 'fg']}
like image 177
mando Avatar answered Sep 28 '22 04:09

mando