api-example.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/python
  2. # Copyright 2013 Christian Berendt
  3. # Copyright 2013 Luke Dashjr
  4. #
  5. # This program is free software; you can redistribute it and/or modify it under
  6. # the terms of the GNU General Public License as published by the Free Software
  7. # Foundation; either version 3 of the License, or (at your option) any later
  8. # version. See COPYING for more details.
  9. import argparse
  10. import json
  11. import logging
  12. import pprint
  13. import socket
  14. logging.basicConfig(
  15. format='%(asctime)s %(levelname)s %(message)s',
  16. level=logging.DEBUG
  17. )
  18. parser = argparse.ArgumentParser()
  19. parser.add_argument("command", default="summary", nargs='?')
  20. parser.add_argument("parameter", default="", nargs='?')
  21. parser.add_argument("--hostname", default="localhost")
  22. parser.add_argument("--port", type=int, default=4028)
  23. args = parser.parse_args()
  24. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  25. try:
  26. s.connect((args.hostname, args.port))
  27. except socket.error, e:
  28. logging.error(e)
  29. try:
  30. s.send("{\"command\" : \"%s\", \"parameter\" : \"%s\"}"
  31. % (args.command, args.parameter)
  32. )
  33. except socket.error, e:
  34. logging.error(e)
  35. data = ''
  36. while True:
  37. try:
  38. newdata = s.recv(1024)
  39. if newdata:
  40. data += newdata
  41. else:
  42. break
  43. except socket.error, e:
  44. break
  45. try:
  46. s.close()
  47. except socket.error,e:
  48. logging.error(e)
  49. if data:
  50. data = json.loads(data.replace('\x00', ''))
  51. pp = pprint.PrettyPrinter()
  52. pp.pprint(data)