2

I'm new to python and want to handle variable number of arguments for a python code such that a string like this can be handled -

python abc.py -20 input1.txt input2.txt .. output.txt

-20 is optional. There has to be at least one input file, but there can be any number of those and a necessary output file at the end. I looked at argparse, and I can do fixed arguments or optional but unable to figure it out for this case.

3
  • 2
    what does the -20 signify? With something this simple, just looking at sys.argv might be good enough ... Commented Jan 29, 2013 at 0:35
  • Must the interface work exactly like this? It will be ugly to do it exactly like this with argparse, but if you don't mind to change the CLI into a more standard format, it will be easy. Commented Jan 29, 2013 at 0:47
  • yup, sys.srgv worked perfectly. Commented Jan 31, 2013 at 1:44

2 Answers 2

4

Add nargs='+' for variable number arguments.

parser.add_argument("input", nargs='+')
parser.add_argument("output")

$ ./test.py input1 input2 input3 output
Namespace(input=['input1', 'input2', 'input3'], output='output')
Sign up to request clarification or add additional context in comments.

Comments

0

Use argparse. Here's an example from argparse docs:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Run:

$ prog.py 1 2 3 4
4

$ prog.py 1 2 3 4 --sum
10

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.