Best way to make argument parser accept absolute number and percentage?

2024/10/6 7:23:42

I am trying to write a Nagios style check to use with Nagios. I have working script that takes in something like -w 15 -c 10 and interprets that as "Warning at 15%, Critical at 10%". But I just realized that in the built-in Nagios plugins, the same arguments would mean "Warning at 15MB, Critical at 10MB"; I would instead need to enter -w 15% -c 10% to get the above behavior.

So my question is, what is the best way to make my script behave like the built-in Nagios scripts? The only way I can think of is accepting the argument as a string and parsing it, but is there a neater way?

Answer

You can use your own class as type for the arguments:

import argparseclass 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.01return valueparser = 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.15python 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
https://en.xdnf.cn/q/119974.html

Related Q&A

Python calculating prime numbers

I have to define a function called is_prime that takes a number x as input, then for each number n from 2 to x - 1, test if x is evenly divisible by n. If it is, return False. If none of them are, then…

Why am I getting a column does not exist error when it does exist? I am modifying the Flask tutorial

I have a column named ticker_symbol, but I am getting a error when I run the error that there is no such column. Here is my auth.py code so far. It is similar to the Flask tutorial code. I get my get_d…

Update Key Value In Python In JSON File

How do I change a value in a json file with python? I want to search and find "class": "DepictionScreenshotsView" and replace it with "class": ""JSON File:{&quo…

Getting UnboundLocalError: local variable age referenced before assignment error

Ive written a simple script with TKinter and SQLAlchemy, where an sqlite .db is created, saving Employee information such as name, age, address, etc, etc.I realized that if a user puts a string in the …

Cannot run python script [duplicate]

This question already has answers here:What does "SyntaxError: Missing parentheses in call to print" mean in Python?(11 answers)Closed 9 years ago.I am trying to run this python script:https…

I want to read multiple audio files with librosa and then save it into an empty list

Here id my code . when I append into the array the array remain empty . Please help me where is the mistake. Or tell me some other way also to do thisA = [] # load more files with librosa pathAudio = …

How to db.execute in postgresql using the LIKE operator with variables within flask [duplicate]

This question already has an answer here:CS50: LIKE operator, variable substitution with % expansion(1 answer)Closed 4 years ago.Im trying to get my db.execute to work but encounter a syntax error when…

C, Perl, and Python similar loops different results

I wrote scripts to calculate pi in python, perl and c. They all use the same algorithm (trapezoidal reimann sum of a circle with n subintervals) and the python and perl programs always get the same re…

How to print a single backslash in python in a string? [duplicate]

This question already has answers here:Why do backslashes appear twice?(2 answers)Closed 1 year ago.In python (3x version)\ # this is error no doubt \\ # this prints two backslashes ,i.e., \\ r\ # thi…

Return nested JSON item that has multiple instances

So i am able to return almost all data, except i am not able to capture something like this:"expand": "schema""issues": [{"expand": "<>","id…