api-example.py 1.4 KB

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