prompt.py 2.1 KB

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