Python Program for Key Value Pair Arguments

Key Value Pair Arguments and using unit converter in Python Program

This python program is used to convert the memory size in KB using pint module for UNIT_CONVERTER and gets user input as key value pair.

# Python program to convert memory size in KB

import sys
import pint

UNIT_CONVERTER = pint.UnitRegistry(filename=None)
UNIT_CONVERTER.define('kB = []')
UNIT_CONVERTER.define('KB = []')
UNIT_CONVERTER.define('MB = 1024 KB')
UNIT_CONVERTER.define('GB = 1048576 KB')

def convert_memory_unit_in_kb(mem_val):
    memory_kb = int(UNIT_CONVERTER(mem_val).to_base_units())
    return memory_kb

def get_key_value_args(args):
    dict = {}
    while args:
        if args[0].startswith('--'):
            dict[args[0].strip(' -')] = args[1].strip(' ')
        args = args[1:]
    return dict

if __name__ == '__main__':
    args = get_key_value_args(sys.argv)
    mem_size_kb = convert_memory_unit_in_kb(args['mem_size'])
    print('Memory size in KB:' + str(mem_size_kb));

$ python --mem_size 242424MB
Memory size in KB:248242176

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter