Monday, April 15, 2024
HomeSoftware EngineeringKey-Worth CLI Arguments in Python

Key-Worth CLI Arguments in Python


In case you have a CommandLine software (CLI) written in Python, you have got numerous methods which you can take arguments from the person.

You would take the order from the person and assign these to variables:

import sys
print( sys.argv )

This will provide you with an inventory of all of the area separated values.

So in case your app known as like:

python app.py var1 var2
# ['app.py', 'var1', 'var2']

As you’ll be able to see, sys.argv is an inventory and the arguments begin from the second index location.

print( sys.argv[1] )
# var1

How can we use Key-Worth Arguments as an alternative?

What if our app’s person decides to swap the order of var1 and var2? Or in the event that they miss one thing out?

How about we give them a key as effectively?

python app.py var1=someValue var2=someOtherValue

That appears nicer, however how will we implement this in code?

import sys

kw_dict = {}
for arg in sys.argv[1:]:
    if '=' in arg:
        sep = arg.discover('=')
        key, worth = arg[:sep], arg[sep + 1:]
        kw_dict[key] = worth

We now have a dictionary that comprises every of the key-value pairs.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments