Key-Value CLI Arguments in Python

0 min read 180 words

If you have a CommandLine application (CLI) written in Python, you have a number of ways that you can take arguments from the user.

You could take the order from the user and assign those to variables:

import sys
print( sys.argv )

This will give you a list of all the space separated values.

So if your app is called like:

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

As you can see, sys.argv is a list and the arguments start from the second index location.

print( sys.argv[1] )
# var1

How can we use Key-Value Arguments instead?

What if our app’s user decides to swap the order of var1 and var2? Or if they miss something out?

How about we give them a key as well?

python app.py var1=someValue var2=someOtherValue

That seems nicer, but how do we implement this in code?

import sys

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

We now have a dictionary that contains each of the key-value pairs.

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags