This repository has been archived by the owner on Nov 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
Custom Options
fmoo edited this page Nov 2, 2012
·
2 revisions
Custom options (and command line options) can be created with the help of the property()
function. It's usable on both services and tasks.
from sparts.tasks.periodic import PeriodicTask
from sparts.vservice import VService
from sparts.sparts import option
import socket
class HostCheckTask(PeriodicTask):
INTERVAL = 5
check_name = option('check-name', default=socket.getfqdn(), type=str,
help='Name to check [%(default)s]')
def execute(self, *args, **kwargs):
self.logger.info("LOOKUP %s => %s", self.check_name,
socket.gethostbyname(self.check_name))
class DNSChecker(VService):
TASKS=[HostCheckTask]
DNSChecker.initFromCLI()
Running with -h shows:
> python option_example.py -h
usage: option_example.py [-h] [--tasks [TASK [TASK ...]]] [--level LEVEL]
[--dryrun]
[--HostCheckTask-check-name HOSTCHECKTASK_CHECK_NAME]
[--HostCheckTask-interval SECONDS]
optional arguments:
-h, --help show this help message and exit
--tasks [TASK [TASK ...]]
Tasks to run. Pass without args to see the list. If
not passed, all tasks will be started
--level LEVEL Log Level [DEBUG]
--dryrun Run in "dryrun" mode
--HostCheckTask-check-name HOSTCHECKTASK_CHECK_NAME
Name to check [pete-P35C-DS3R]
--HostCheckTask-interval SECONDS
How often this task should run [5] (s)
And running the program:
> python option_example.py --HostCheckTask-check-name sphotos-a.xx.fbcdn.net
DEBUG:DNSChecker:All tasks started
INFO:DNSChecker.HostCheckTask:LOOKUP sphotos-a.xx.fbcdn.net => 31.13.69.58
In some cases (like with PeriodicTask
) it's convenient to provide options with overridable defaults.
The trick to doing this is currently a kind of a hack; you need to set a callable that explicitly takes the class as the first parameter. This allows something like this to work:
class MyTask(PeriodicTask):
DEFAULT_PORT = 80
port = option('port', default=lambda cls: cls.DEFAULT_PORT)
class MyOtherTask(MyTask):
DEFAULT_PORT = 8080