Parsing command line input for numbers

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

$ myapp -n 3,4,5,6 

or

 $ myapp -n 3-6 

I want my application to put them in a Python list, for example, [3, 4, 5, 6] I use optparse , but I don’t know how to create a list of these two input styles. Some sample code would be great.

EDIT

I would also like to introduce several ranges:

 $ myapp -n 22-27, 51-64 
+8
python command-line parsing
source share
5 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) 

gives

 % 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] 
+13
source share

If you have n-arg in a line you can do:

 def f(s): if '-' in s: i = s.index('-') return range(*map(int, s.split('-'))) return map(int, s.split(',')) 

Some examples:

 In [3]: s = '1, 2, 3, 4, 5, 6' In [4]: f(s) Out[4]: [1, 2, 3, 4, 5, 6] In [5]: f('3-6') Out[5]: [3, 4, 5] In [6]: f('3-16-3') Out[6]: [3, 6, 9, 12, 15] 
+3
source share

You can define your argument and use optparse callback to process the input before saving it:

 from optparse import OptionParser parser = OptionParser() def create_range_callback(option, opt, value, parser): i, j = map(int, value.split('-')) setattr(parser.values, option.dest, range(i, j+1)) parser.add_option("-r", "--range", action="callback", callback=create_range_callback, type="string", dest='list') (options, args) = parser.parse_args() print options.list 

now:

 python2.7 test.py -r 1-5 

Output:

 [1, 2, 3, 4, 5] 
+2
source share

Use the Python range function . Parse your user input by dividing it by a β€œ-” character, and then pass these parameters to a range.

Your code might look something like this:

 parameters = input.split('-') completeRange = range(int(parameters[0]), int(parameters[1])) 

If they enter individual numbers, you can simply just make it out from the list.

+1
source share

You can use the optparse library.

Example:

 from optparse import OptionParser opt_parser = OptionParser(version="%prog 0.1") opt_parser.usage = '%prog [options]\n\nTCP protocol reengineering tool' # Options opt_parser.add_option('-n', default="1,2,3") (options, args) = opt_parser.parse_args() list = [] for s in options.n.split(","): list.append(int(s)) 
+1
source share

Source: https://habr.com/ru/post/651214/


All Articles