I want to pass 2 lists of integers as input to a python program.
For e.g, (from command line)
python test.py --a 1 2 3 4 5 -b 1 2
The integers in this list can range from 1-50, List 2 is subset of List1.
Any help/suggestions ? Is argparse
the right module ? Any concerns in using that ?
I have tried :
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--a', help='Enter list 1 ')
parser.add_argument('--b', help='Enter list 2 ')
args = parser.parse_args()
print (args.a)
You can pass them as strings than convert to lists. You can use argparse or optparse.
Example:
python prog.py --l1=1,2,3,4
Also,as a line you can pass something like this 1-50 and then split on '-' and construct range. Something like this:
Example:
python prog.py --l1=1-50
Logic I think you can write yourself. :)
The way that
optparse
andargparse
work is they read arguments from the command line, arguments are split by white-space, so if you want to input your list of integers through the command line interfact fromoptparse
orargparse
- you can do this by removing the spaces, or by surrounding your argument with"
, example:or:
Your script then needs to convert these inputs into an actual list.
Using
argparse
syntax (very similar foroptparse
):Another way to do this would be by either importing the module you want to run and passing the list objects to a class that deals with your code, or by using a while loop and
raw_input
/input
to collect the desired list.argparse
supportsnargs
parameter, which tells you how many parameters it eats. Whennargs="+"
it accepts one or more parameters, so you can pass-b 1 2 3 4
and it will be assigned as a list tob
argumentSo you can run:
And this is valid:
If the only arguments are the lists and the separators, you can do it relatively simply:
Adding validation is easy:
Producing a help message:
This worked for me:
parser.add_argument('-i', '--ids', help="A comma separated list IDs", type=lambda x: x.split(','))
EDIT:
I have just realised that this doesn't actually answer the question being asked. Jakub has the correct solution.
Just adding this one for completeness. I was surprised that I didn't see this approach.
This just a basic example, but you can also add validation or transform values in someway such as coercing them to uppercase.