Key-Value CLI Arguments in Python

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 )
Code language: Python (python)

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']
Code language: Python (python)

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

print( sys.argv[1] ) # var1
Code language: Python (python)

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
Code language: Python (python)

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
Code language: Python (python)

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments