I'm writing a python script where I want to pass in a list of tuples/list. I tried using the argparse module, but couldn't find a way to pass in a list of tuples as an argument (i.e. [(1,2),(3,4),(5,6)]).
What I've tried so far:
- I know I can use
nargs='+'but that only enables me to pass in a list of values. - I tried
parser.add_argument('--pairs', type=tuple, nargs='+'), but I get
$ python test.py --pairs (1,2) (2,4)
-bash: syntax error near unexpected token `('
Does anyone have any examples that uses the argparse module (or any other module for that matter)?
Here's the script. Nothing special, just wanted to pass in the list of tuples and make sure I can print and access the elements properly:
import argparse
def test(args):
print("----")
print(args.pairs)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--pairs', type=tuple, nargs='+')
args = parser.parse_args()
print("===args===")
for arg in vars(args):
print(arg, getattr(args, arg))
test(args)