What is the best way to handle command line arguments in Python?

February 10, 2018 - 1 minute read -
cli python blog

The best way to handle command line arguments with Python is [defopt](http://evanunderscore/defopt: Effortless argument parser). It works like magic. You write a function, add a proper docstring using any standard format (I use [numpy doc]), and see the magic

[code language=”python”]

import defopt

def main(greeting, *, count=1): “"”Display a friendly greeting.

:param str greeting: Greeting to display
:param int count: Number of times to display the greeting
"""
for _ in range(count):
    print(greeting)

if name == ‘main’: defopt.run(main)
[/code]

You have:

* help string generation
* data type conversion
* default arguments
* zero boilerplate code

Magic!

Illustration: the famous XKCD