Skip to main content

Python cli scripts for humans

Project description

Captain

Easy python cli scripts for people that just want get things done.

Usage

A valid captain cli script needs just two things:

  1. A Default class that extends captain.Command and has a handle() method (can be async):

    from captain import Command
    
    class Default(Command):
        async def handle(self, foo, bar):
            return 0
    
  2. Calling captain.application() at the end of your script:

    from captain import Command, application
    
    class Default(Command):
        async def handle(self, foo, bar):
            return 0
    
    if __name__ == "__main__":
        application()
    

That's it! Whatever arguments you define in your class's Default.handle() method will be options on the command line. A captain script is called just like any other python command line script, so to run the above example you could do:

$ python path/to/script.py --foo=1 --bar=2

Argument Decorator

The captain.arg() decorator provides a nice passthrough api to the full argparse.ArgumentParser.add_argument() method if you want to fine tune how arguments are passed into your script:

from captain import Command, application, arg

class Default(Command):
    @arg('--foo', '-f', action="store_true")
    @arg('arg', metavar='ARG')
    async def handle(self, *args, **kwargs):
        '''this is the help description'''
        self.output.out(args)
        self.output.out(kwargs)

if __name__ == "__main__":
    application()

Would print a help string like this:

usage: script.py [-h] [--foo FOO] ARG

this is the help description

positional arguments:
  ARG

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

Command Output

The captain.io.Output class makes it easy to print stuff in your script while still giving you full control by being able to configure the logger if you need to. It also will obey the global --quiet flag that Captain adds to every script.

It's available in the handle() method by using self.output:

from captain import Command

class Default(Command):
    async def handle(self, *args, **kwargs):
        var1 = "print"

        var2 = "stdout"
        self.output.out("this will {} to {}", var1, var2)

        var2 = "stderr"
        self.output.err("this will {} to {}", var1, var2)

        e = ValueError("this will print with stacktrace and everything")
        self.output.exception(e)

The captain.io.Output class has a lot of nice little helper methods but Captain can also work with modules like clint if you need to do more advanced cli output.

Examples

A typical python cli script

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='fancy script description')
    parser.add_argument("--foo", action='store_true')
    parser.add_argument("--bar", default=0, type=int)
    parser.add_argument("args", nargs='*')
    args = parser.parse_args()
    sys.exit(0)

would become:

import captain

class Default(captain.Command):
    async def handle(foo=False, bar=0, *args):
        '''fancy script description'''
        return 0

if __name__ == '__main__':
    captain.application()

Subcommands

Captain supports multiple subcommands defined in the script by naming your captain.Command child classes something other than Default:

# cli.py

import captain

class Foo(captain.Command):
    async def handle(self):
        pass

class Bar(captain.Command):
    async def handle(self):
        pass

if __name__ == '__main__':
    captain.application()

So foo could be called using:

$ python cli.py foo

And bar could be called using:

$ python cli.py bar

Embedding captain in another package

If you want a script from you package to be usable using both python -m example and maybe a console_scripts entry point defined in setup.py, you can set up your package's __main__.py module like this:

# example/__main__.py

from captain import Command, application

class Default(captain.Command):
    async def handle(self):
        pass
        
if __name__ == "__main__":
    application()

And then in your setup.py script you can add:

entry_points = {
    'console_scripts': [
        'example = example.__main__:application'
    ],
}

That's all there is to it.

Install

Use pip:

$ pip install captain

For latest and greatest:

$ pip install -U "git+https://github.com/Jaymon/captain#egg=captain"

Project details


Download files

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

Source Distribution

captain-5.2.0.tar.gz (29.1 kB view details)

Uploaded Source

Built Distribution

captain-5.2.0-py3-none-any.whl (31.2 kB view details)

Uploaded Python 3

File details

Details for the file captain-5.2.0.tar.gz.

File metadata

  • Download URL: captain-5.2.0.tar.gz
  • Upload date:
  • Size: 29.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.10

File hashes

Hashes for captain-5.2.0.tar.gz
Algorithm Hash digest
SHA256 568f304c222b41000ba382f6d46889d2c28e6b340bc16b588f385a5e4b06196c
MD5 63ab9683e0330f9f186785dde94fa2ba
BLAKE2b-256 8077402a4190fa06a418a884cd0ac5841997c439e3371ff5da43c0ea336f0b65

See more details on using hashes here.

File details

Details for the file captain-5.2.0-py3-none-any.whl.

File metadata

  • Download URL: captain-5.2.0-py3-none-any.whl
  • Upload date:
  • Size: 31.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.10

File hashes

Hashes for captain-5.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f9b4a32a2c9be084acb62f6e5f08590228ec594f12e32382e0b2ceceaa006610
MD5 4868867d0aea56cb1eebfe3a90d2feda
BLAKE2b-256 b895922c9a9d54681a89847ff990a8913e8bc32888c175ea9d78e88a152243fe

See more details on using hashes here.

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