watch.py 1.71 KiB
#!/usr/bin/env python
#coding=utf8
'''
CloudControl watch command
'''
import sys
import time
from cccli.exception import *
from sjrpc.core.exceptions import *
from cccli.printer import Printer, color
from cccli.command import OptionCommand
from cStringIO import StringIO
class Command_watch(OptionCommand):
'''Show output of a repeated command'''
def __init__(self, cli, argv0):
OptionCommand.__init__(self, cli, argv0)
self.set_usage("%prog [options] command [options]")
self.add_option("-n", "--interval", dest="interval", type="float", default=1.0,
help="Define interval in seconds")
def __call__(self, argv):
# Parse argline
self.parse_args(argv)
if len(self.args) == 0:
raise cmdBadArgument()
if self.options.interval < 0.5:
raise cmdBadArgument("Interval must be >= 0.5")
while True:
# Substitute aliases
self.args = self.cli.aliases.substitute(self.args)
# Put the fd of a buffer in sys.stdout and sys.err instead of the tty fd
sys.stderr = sys.stdout = StringIO()
try:
# Clear tty
self.printer.clear()
# Execute command and write output in the buffer
self.cli.commands(self.args)
# Print the buffer
self.printer.out(sys.stdout.getvalue(), fd=sys.__stdout__)
# Wait
time.sleep(self.options.interval)
except KeyboardInterrupt:
raise
except cliException:
raise
finally:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__