3

I have some python script foo.py with many arguments. Inside that script I am using argparse import ArgumentParser to parse them.

I want to pass an array as the value of one of them from bash. I have tried:

python foo.py --arg1=1 --arrArg=[1,2] --arg3=x

when I print them inside the script I get:

arg1=1

arrArg=['1',',','2']

arg3=x

How do I pass the arry as numbers from bash?

2 Answers 2

3

If you use the script yourself, and only yourself, then you can use eval(). But watch out, this is not a very safe function. Don't ever use this when you don't know what the input is.

import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--arr',
                help='Array of integers')

args = parser.parse_args()
data = eval(args.arr)
print(type(data))
print(data)

Otherwise, use the nargs='+' argument for argparse:

import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--arr', nargs='+', type=int,
                    help='Array of integers')

args = parser.parse_args()
data = args.arr
print(type(data))
print(data)

And call your script with python foo.py --arr 1 2 3 --bla blablabla

Sign up to request clarification or add additional context in comments.

1 Comment

I have actually used nargs=n, where n is my array length but only thanks to your answer.
2

There are few ways you can do this: using nargs or using action=append:

import argparse

parser = argparse.ArgumentParser()

# You can specify number of elements in an array.
# '+' == 1 or more.
# '*' == 0 or more.
# '?' == 0 or 1.
# An int is an explicit number of elements to accept.
parser.add_argument('--nargs', nargs='+')

# To make the input integers
parser.add_argument('--nargs-int-type', nargs='+', type=int)

# Using `action=append`. But out must provide the flag for every
# input. And you can use type=int here as well.
parser.add_argument('--append-action', action='append')

# To show the results
for _, value in parser.parse_args()._get_kwargs():
    if value is not None:
        print(value)

And the results will look like this:

$ python arg.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']

$ python arg.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]

$ # Negative numbers are also handled
$ python arg.py --nargs-int-type -1234 2345 -3456 4567
[-1234, 2345, -3456, 4567]

$ python arg.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']

Reference: https://docs.python.org/3/library/argparse.html#nargs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.