Daemon manager (example)
Below is an example of a simple daemon manager, written with argumentor. The code itself does nothing, since its primary goal is to provide an example on how to use argumentor.
d-manager.py
#!/usr/bin/env python3
import sys
from argumentor import Argumentor, Flags
from argumentor.exc import ParsingError
argm = Argumentor("d-manager")
argm.add_command(
"start",
description="start daemon",
)
argm.add_command(
"stop",
description="stop daemon",
)
argm.add_command(
"msg",
description="send message to daemon",
value_type=list,
)
argm.add_command(
"reload",
description="reload daemon",
)
argm.add_command(
"--help",
description="print this help page",
hide=True,
)
argm.add_command_alias("-h", "--help")
argm.add_option(
"--force",
description="force operation",
)
argm.add_option_alias("-f", "--force")
argm.add_option(
"--verbose",
description="be more verbose",
)
argm.add_option_alias("-v", "--verbose")
argm.add_option(
"--help",
description="get contextual help",
flags=Flags.SPECIAL,
)
argm.add_option_alias("-h", "--help")
argm.add_option(
"--config",
command="start",
description="configuration file to use",
value_type=str,
default_value="/etc/d-manager.conf",
)
argm.add_option_alias(
"-c",
"--config",
command="start",
)
argm.add_option(
"--config",
command="reload",
description="configuration file to use",
value_type=str,
default_value="/etc/d-manager.conf",
)
argm.add_option_alias(
"-c",
"--config",
command="reload",
)
argm.add_option(
"--pidfile",
command="start",
description="custom PID file",
value_type=str,
default_value="/var/run/d-manager.pid",
)
argm.add_option_alias(
"-p",
"--pidfile",
command="start",
)
try:
cmd, opts = argm.parse()
except ParsingError as err:
sys.stderr.write(str(err) + "\n")
sys.exit(1)
if cmd.get("--help"):
print(argm.get_help())
elif opts.get("--help"):
single_command = list(cmd.keys())[0]
print(
argm.get_help(
single_command=single_command, print_options_for_command=single_command
)
)
elif cmd.get("start"):
print(
f"starting daemon with config {opts.get('--config')} and PID file {opts.get('--pidfile')}"
)
elif cmd.get("stop"):
print("stopping daemon")
elif cmd.get("msg"):
print(f"sending message(s) to daemon: {cmd.get('msg')}")
elif cmd.get("reload"):
print(f"reloading daemon with config {opts.get('--config')}")
else:
sys.stderr.write(
"error: no command specified\nrun with --help to view available commands\n"
)
sys.exit(1)