prompt.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import urllib
  2. import urllib2
  3. import threading
  4. import subprocess
  5. import os
  6. def local_print(string):
  7. if os.name == "posix":
  8. # Nicer colour output when using posix (and thus supporting colour)
  9. string = "\033[92m%s\033[0m" % string
  10. print(string)
  11. def remote_print(string):
  12. if os.name == "posix":
  13. # Nicer colour output when using posix (and thus supporting colour)
  14. string = "\033[94m%s\033[0m" % string
  15. print(string)
  16. local_print("Welcome to the local shell!")
  17. local_print("Please specify Modelverse location (default: localhost:8001)")
  18. location = raw_input()
  19. if location == "":
  20. address = "localhost"
  21. port = 8001
  22. else:
  23. address, port = location.strip().split(":")
  24. local_print("Username (default: test)")
  25. username = raw_input()
  26. if username == "":
  27. username = "test"
  28. else:
  29. username = username.strip()
  30. # If user shouldn't exist yet, we create it
  31. urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "set_input", "element_type": "V", "value": '"%s"' % username, "username": "user_manager"}))).read()
  32. local_print("Switching context to Modelverse: all data is piped.")
  33. local_print("To quit: execute command 'quit'")
  34. def print_output():
  35. while 1:
  36. output = urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "get_output", "username": username}))).read()
  37. l, r = output.split("&", 1)
  38. if "value" in l:
  39. output = l
  40. else:
  41. output = r
  42. _, output = output.split("=", 1)
  43. remote_print("%s" % str(output))
  44. thrd = threading.Thread(target=print_output)
  45. thrd.daemon = True
  46. thrd.start()
  47. while 1:
  48. command = raw_input()
  49. if command == "quit":
  50. local_print("Received quit: breaking connection to Modelverse immediately!")
  51. break
  52. try:
  53. # Could be a number
  54. _ = float(command)
  55. command = str(command)
  56. local_print("Interpreting value as a number")
  57. except:
  58. if len(command) > 0 and command[0] == "\\":
  59. command = '{"value": "%s"}' % command[1:]
  60. else:
  61. command = '"%s"' % command
  62. local_print("Got command string: " + str(command))
  63. urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "set_input", "element_type": "V", "value": command, "username": username}))).read()