prompt.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. # If user shouldn't exist yet, we create it
  37. urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "set_input", "element_type": "V", "value": '"%s"' % username, "username": "user_manager"}))).read()
  38. local_print("Switching context to Modelverse: all data is piped.")
  39. local_print("To quit: execute command 'quit'")
  40. def print_output():
  41. while 1:
  42. output = urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "get_output", "username": username}))).read()
  43. l, r = output.split("&", 1)
  44. if "value" in l:
  45. output = l
  46. else:
  47. output = r
  48. _, output = output.split("=", 1)
  49. remote_print("%s" % str(output))
  50. thrd = threading.Thread(target=print_output)
  51. thrd.daemon = True
  52. thrd.start()
  53. while 1:
  54. command = raw_input()
  55. if command == "quit":
  56. local_print("Received quit: breaking connection to Modelverse immediately!")
  57. break
  58. try:
  59. # Could be a number
  60. _ = float(command)
  61. command = str(command)
  62. local_print("Interpreting value as a number")
  63. except:
  64. if len(command) > 0 and command[0] == "\\":
  65. command = '{"value": "%s"}' % command[1:]
  66. else:
  67. command = '"%s"' % command
  68. local_print("Got command string: " + str(command))
  69. urllib2.urlopen(urllib2.Request("http://%s:%s/" % (address, port), urllib.urlencode({"op": "set_input", "element_type": "V", "value": command, "username": username}))).read()