prompt.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. def execute(scriptname, parameters=[], wait=False):
  11. if os.name == "nt":
  12. command = ["%s.bat" % scriptname] + parameters
  13. elif os.name == "posix":
  14. command = ["./%s.sh" % scriptname] + parameters
  15. else:
  16. raise Exception("Unknown OS: " + str(os.name))
  17. if wait:
  18. return subprocess.call(command, shell=False)
  19. return subprocess.call(command, shell=False, stdout=open('/tmp/output', 'w'), stderr=open('/tmp/output', 'w'))
  20. else:
  21. return subprocess.Popen(command, shell=False, stdout=open('/tmp/output', 'w'))
  22. local_print("Welcome to the local shell!")
  23. local_print("Please specify Modelverse location (default: localhost:8001)")
  24. location = raw_input()
  25. if location == "":
  26. address = "localhost"
  27. port = 8001
  28. else:
  29. address, port = location.strip().split(":")
  30. local_print("Username (default: test)")
  31. username = raw_input()
  32. if username == "":
  33. username = "test"
  34. else:
  35. username = username.strip()
  36. local_print("Switching context to Modelverse: all data is piped.")
  37. local_print("To quit: execute command 'quit'")
  38. def print_output():
  39. while 1:
  40. output = urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "get_output", "username": username}))).read()
  41. l, r = output.split("&", 1)
  42. if "value" in l:
  43. output = l
  44. else:
  45. output = r
  46. _, output = output.split("=", 1)
  47. remote_print("%s" % str(output))
  48. thrd = threading.Thread(target=print_output)
  49. thrd.daemon = True
  50. thrd.start()
  51. while 1:
  52. command = raw_input()
  53. if command == "quit":
  54. local_print("Received quit: breaking connection to Modelverse immediately!")
  55. break
  56. try:
  57. # Could be a number
  58. _ = float(command)
  59. command = str(command)
  60. local_print("Interpreting value as a number")
  61. except:
  62. if len(command) > 0 and command[0] == "\\":
  63. command = '{"value": "%s"}' % command[1:]
  64. else:
  65. command = '"%s"' % command
  66. local_print("Got command string: " + str(command))
  67. urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "set_input", "element_type": "V", "value": command, "username": username}))).read()