Writing

Building a Python CLI #1: argparse

This tutorial was written in 2019. Python and library APIs may need changes to run these examples today.

Python includes argparse for building command-line interfaces. Create a hello package with __init__.py and main.py:

hello/
└── hello/
    ├── __init__.py
    └── main.py

argparse

A parser defines a positional name argument and passes it to a greeting function:

# hello/main.py

import argparse

def hello(name):
    print("Hello, {}".format(name))

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('name')
    args = parser.parse_args()

    name = args.name
    hello(name)

if __name__ == "__main__":
    main()

Run it with a name:

$ python main.py SJQuant
>> Hello, SJQuant

The parser also supplies a help option:

$ python main.py --help

>>
usage: main.py [-h] name

positional arguments:
  name

optional arguments:
  -h, --help  show this help message and exit

(click_tutorial)  E:\dev\python-cli\ex1>python main.py --help
usage: main.py [-h] name

positional arguments:
  name

optional arguments:
  -h, --help  show this help message and exit

Add a help argument to describe the positional argument:

...
parser.add_argument('name', help="Write name you want to say Hello.")
...
$ python main.py --help
>>
...
positional arguments:
  name        Write name you want to say Hello.
...

The longer version adds a version option and mutually exclusive greeting and farewell options:

import argparse
import sys

def hello(name):
    print("Hello, {}".format(name))

def bye(name):
    print('Good bye, {}'.format(name))

def main():
    parser = argparse.ArgumentParser()



    parser.add_argument(
        'name', nargs='?', default=False, help="Write name you want to say Hello.")



    parser.add_argument('-v', '--version', action="store_true",
                        help="Show version of this program")



    group = parser.add_mutually_exclusive_group()
    group.add_argument('--hello', action="store_true", help="say hello")
    group.add_argument('--bye', action="store_true", help="say good bye")

    args = parser.parse_args()

    name = args.name

    if args.version:
        print('1.0.0')
        sys.exit()

    if not name:
        parser.print_help()
        sys.exit()


    # say goodbye
    if args.bye:
        bye(name)
    else:
        hello(name)

if __name__ == "__main__":
    main()
$ python main.py --version

>> 1.0.0
$ python main.py SJQuant --hello

>> Hello, SJQuant
$ python main.py SJQuant --bye

>> Good bye, SJQuant

Define setup.py

To expose a hello command, put setup.py alongside the package and declare a console_scripts entry point:

hello/
├── setup.py
└── hello/
    ├── __init__.py
    └── main.py
from setuptools import setup, find_packages

setup(

    name='hello',

    version='1.0.0',
    author='SJQuant',
    author_email='seonujang92@gmail.com',
    description='Greet someone',
    packages=find_packages(),

    entry_points={
        "console_scripts": [


            "hello = hello.main:main"
        ]
    },
    classifiers=[
        'Programming Language :: Python :: 3',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
    ],
)

Install from the project directory. A virtual environment makes the command available within that environment:

$ python -m pip install .
$ hello --help

>>
usage: hello [-h] [-v] [--hello | --bye] [name]

positional arguments:
  name           Write name you want to say Hello.

optional arguments:
  -h, --help     show this help message and exit
  -v, --version  Show version of this program
  --hello        say hello
  --bye          say good bye
$ hello sjquant --hello
>> Hello, sjquant

$ hello sjquant --bye
>> Good bye, sjquant

See the Python argparse tutorial for more options. The next post explores Click.