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, code=1)
Raised to exit the process with the specified message and exit code.
- Parameters:
message (
str) – the error message.code (
int) – the script exit code.
- class toolrack.script.Script(stdout=None, stderr=None)
Wraps a python script handling argument parsing.
Subclasses must implement
get_parser()andmain()methods.Inside
main(),ErrorExitMessagecan be raised with the appropriatemessageandcodeto 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.argvif not provided).- exit(code=0)
Exit with the specified return code.
- Return type:
None
- get_parser()
Return a configured
argparse.ArgumentParserinstance. :rtype:ArgumentParserNote
Subclasses must implement this method.
- handle_keyboard_interrupt(interrupt)
Called when a
KeyboardInterruptis raised.By default it just traps the exception and exits with success. It can be overridden to perform additional cleanups.
- main(args)
The body of the script.
It gets called with the
argparse.Namespaceinstance returned byget_parser().- Parameters:
args (
Namespace) – command line arguments.- Return type:
int|None
Note
Subclasses must implement this method.