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
Example: Numeric Command-Line Argumentsint argument = Intege. parseInt(str); Here, the parseInt() method of the Integer class converts the string argument into an integer.
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() .
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With