Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing command line input for numbers

I'm writing a command line application and would like the user to be able to enter numbers as individual numbers or as a range. So, for example:

$ myapp -n 3,4,5,6

or

$ myapp -n 3-6

I would like my app to put these into a Python list e.g., [3, 4, 5, 6] I'm using optparse, but am not sure how to create the list from these two styles of inputs. Some example code would be great.

EDIT

I would like to be able to enter multiple ranges too:

$ myapp -n 22-27, 51-64
like image 585
normski Avatar asked Jan 18 '11 16:01

normski


People also ask

How do you take integer inputs using command line arguments?

Example: Numeric Command-Line Argumentsint argument = Intege. parseInt(str); Here, the parseInt() method of the Integer class converts the string argument into an integer.

How do you pass arguments to Argparse?

After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() .

How do you add an optional argument in Argparse?

Python argparse optional argument The module is imported. An argument is added with add_argument . The action set to store_true will store the argument as True , if present. The help option gives argument help.


1 Answers

import argparse

def parse_range(astr):
    result = set()
    for part in astr.split(','):
        x = part.split('-')
        result.update(range(int(x[0]), int(x[-1]) + 1))
    return sorted(result)

parser = argparse.ArgumentParser()
parser.add_argument('-n', type=parse_range)
args = parser.parse_args()
print(args.n)

yields

% script.py -n 3-6
[3, 4, 5, 6]

% script.py -n 3,6
[3, 6]

% script.py -n 22-27,51-64 
[22, 23, 24, 25, 26, 27, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64]
like image 87
unutbu Avatar answered Oct 22 '22 15:10

unutbu