You can use your own class as type for the arguments:
import argparse
class Percent(object):
def __new__(self, percent_string):
if not percent_string.endswith('%'):
raise ValueError('Need percent got {}'.format(percent_string))
value = float(percent_string[:-1]) * 0.01
return value
parser = argparse.ArgumentParser(description="with percent")
parser.add_argument('-w', '--warning', type=Percent)
parser.add_argument('-c', '--critcal', type=Percent)
args = parser.parse_args()
print(args.warning)
Output:
python parse_percent.py -w 15%
0.15
python parse_percent.py -w 15
usage: parse-percent.py [-h] [-w WARNING] [-c CRITCAL]
parse-percent.py: error: argument -w/--warning: invalid Percent value: '15'
Version that works with percent or MB
class Percent(object):
def __new__(self, percent_string):
if percent_string.endswith('%'):
return float(percent_string[:-1]), 'percent'
else:
return float(percent_string), 'MB'
parser = argparse.ArgumentParser(description="with percent")
parser.add_argument('-w', '--warning', type=Percent)
parser.add_argument('-c', '--critcal', type=Percent)
args = parser.parse_args()
value, unit = args.warning
print('{} {}'.format(value, unit))
Output:
python parse_percent.py -w 15
15.0 MB
python parse_percent.py -w 15%
15.0 percent
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…