Skip to main content

Automatic command line apps

Project description

knopt

Build command line applications by inspecting function signatures. Inspired by optfunc.

Quick start

To create a simple command line application, annotate a function with knopt.main:

from knopt import main

@main
def cli(input, output, verbose=False):
    if verbose:
        print('input:', input)
        print('output:', output)

Command line arguments are automatically parsed using argparse and passed to the cli function.

To use other features of the argparse library, you can use annotations on arguments. Pure type annotations work as expected:

from knopt import main

@main
def double(number: int):
    print(number * 2)

but for more control, you can use knopt.arg as an annotation and include options for argparse:

from knopt import main, arg

@main
def search(directory: arg(help="directory to search"),
           invert: arg('v', help="invert match") = False,
           pattern: arg('e', help="search pattern") = ''):
    """search files in a directory"""
    print("searching",
          ("~" if invert else "") + repr(pattern),
          "in", directory)

Note that the docstring of search is used as a description for the program.

Commands

You can also create a program accepting multiple commands by using the knopt.main annotation on a class. Every method of the class is converted to a command. For example:

from knopt import main

@main
class Program:
    """An example program with commands"""

    def __init__(self, verbose: arg('v') = False):
        self.verbose = verbose
        self.files = []

    def add(self, files: arg(nargs='*')):
        """add files to a repository"""
        if self.verbose:
            print('adding', files)

    def commit(self, all: arg('a') = False):
        """commit files"""
        if self.verbose:
            print('committing')

This creates a program with two commands add and commit, and a global option -v/--verbose.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

knopt-0.3.1-py3-none-any.whl (4.4 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page