A modest string writer

gmon 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/python
  2. """Generic mon echoer
  3. usage: gmon [--format=<format>] [-p|--plain] [-x|--xgp] <command> [<args>...]
  4. Options:
  5. -c, --chars specify limit in characters
  6. --format <format> specify format: plain is a plain text, xgp
  7. is specific for xfce4-genmon-plugin
  8. -p, --plain same as --format=plain
  9. -x, --xgp same as --format=xgp
  10. -h, --help show this screen
  11. --version show version
  12. """
  13. import os
  14. import sys
  15. import imp
  16. import docopt
  17. class PluginData(object):
  18. def __init__(self, cmdargs):
  19. self.args = []
  20. self.fmt = "plain"
  21. self.maxlen = 40
  22. self.name = ""
  23. self._load(cmdargs)
  24. def _load(self, cmdargs):
  25. if cmdargs['--plain']:
  26. self.fmt = "plain"
  27. elif cmdargs['--xgp']:
  28. self.fmt = "xgp"
  29. self.name = cmdargs['<command>']
  30. self.args = cmdargs['<args>']
  31. class Subcommand(object):
  32. def __init__(self, args, pluginpath):
  33. self.plugindata = PluginData(args)
  34. self.name = args['<command>']
  35. self._load_plugin(pluginpath)
  36. def _load_plugin(self, pluginpath):
  37. modpath = "%s/%s.py" % (pluginpath, self.name)
  38. with open(modpath) as fh:
  39. module = imp.load_module(self.name, fh, modpath,
  40. (".py", "r", imp.PY_SOURCE))
  41. self.plugin = module.Plugin(self.plugindata)
  42. def _format_output(self, raw):
  43. suffix = "..."
  44. cooked = raw
  45. if self.plugindata.fmt == "plain":
  46. if len(raw) > self.plugindata.maxlen:
  47. newlen = self.plugindata.maxlen - len(suffix)
  48. cooked = raw[:newlen] + suffix
  49. return cooked
  50. def get_output(self):
  51. return self._format_output(self.plugin.render())
  52. class App:
  53. def __init__(self, args):
  54. self._set_pluginpath()
  55. self.subcommand = Subcommand(args, self.pluginpath)
  56. def _set_pluginpath(self):
  57. mypath = os.path.dirname(os.path.realpath(sys.argv[0]))
  58. path = mypath + "/plugins"
  59. path = os.environ.get("GMON_PLUGINS", path)
  60. self.pluginpath = path
  61. def run(self):
  62. print self.subcommand.get_output()
  63. if __name__ == '__main__':
  64. args = docopt.docopt(__doc__,
  65. version="gmon 0.1",
  66. options_first=True)
  67. app = App(args)
  68. app.run()