toolrack.script

Base class for python scripts.

This module provides a Script class to reduce boilerplate when creating python scripts.

Script instances are callable, and can optionally receive a list of arguments (by default they look at sys.argv).

A typical use of Script is to declare a subclass with the script logic and create an instance:

class MyScript(Script):

    def main(self, args):
       # script logic here
       ...

my_script = MyScript()

The instance can be referenced in setuptools entry_points key:

setup(
    entry_points={'console_scripts': ['my_script=path.to.script:my_script']},
    ...)
exception toolrack.script.ErrorExitMessage(message: str, code: int = 1)

Raised to exit the process with the specified message and exit code.

Parameters:
  • message – the error message.
  • code – the script exit code.
class toolrack.script.Script(stdout: Optional[IO] = None, stderr: Optional[IO] = None)

Wraps a python script handling argument parsing.

Subclasses must implement get_parser() and main() methods.

Inside main(), ErrorExitMessage can be raised with the appropriate message and code to cause the script termination, with the message outputted to standard error.

Script instances are callable, and can be passed the argument list (which defaults to sys.argv if not provided).

exit(code: int = 0)

Exit with the specified return code.

get_parser() → argparse.ArgumentParser

Return a configured argparse.ArgumentParser instance.

Note

Subclasses must implement this method.

handle_keyboard_interrupt(interrupt: KeyboardInterrupt)

Called when a KeyboardInterrupt is raised.

By default it just traps the exception and exits with success. It can be overridden to perform additional cleanups.

main(args: argparse.Namespace)

The body of the script.

It gets called with the argparse.Namespace instance returned by get_parser().

Parameters:args – command line arguments.

Note

Subclasses must implement this method.