Advertisement
Guest User

Untitled

a guest
Aug 5th, 2014
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. class Communicator(object):
  2. ON_POSIX = 'posix' in sys.builtin_module_names
  3. WINDOWS = False
  4. try:
  5. select.poll()
  6. from interruptingcow import timeout
  7. except:
  8. WINDOWS = True
  9. pass
  10.  
  11. def __init__(self, bot_name, command):
  12. self.name = bot_name
  13. self.process = subprocess.Popen(command, stdout=subprocess.PIPE,
  14. stdin=subprocess.PIPE, bufsize=1,
  15. close_fds=Communicator.ON_POSIX,
  16. cwd="bots/"+name+"/")
  17. if not Communicator.WINDOWS:
  18. self.pollin = select.poll()
  19. self.pollin.register(self.process.stdin, select.POLLOUT)
  20.  
  21. def get_response(self):
  22. if Communicator.WINDOWS:
  23. while True:
  24. message = self.process.stdout.readline()
  25. if __debug__:
  26. print "got message:"+message
  27. return message
  28.  
  29. if __debug__: print "waiting for response from " + self.name
  30. try:
  31. with Communicator.timeout(self.time_limit, exception=RuntimeError):
  32. response = self.process.stdout.readline()
  33. if __debug__: print "got response from " + \
  34. self.name + " : " + response.rstrip()
  35. return response
  36. except RuntimeError:
  37. if __debug__: print "gave up on " + self.name
  38. raise RuntimeError(self.name+
  39. " didn't produce a response within one second")
  40.  
  41. def send_message(self, message):
  42. if __debug__: print "send message to " + self.name + " : " + message
  43. if Communicator.WINDOWS:
  44. self.process.stdin.write(message+"\n")
  45. self.process.stdin.flush()
  46. return
  47. try:
  48. with Communicator.timeout(self.time_limit, exception=RuntimeError):
  49. while not self.pollin.poll(0):
  50. time.sleep(0.1)
  51. self.process.stdin.write(message+"\n")
  52. if __debug__: print "sent message to " + self.name
  53. except RuntimeError:
  54. if __debug__: print "gave up on " + self.name
  55. raise RuntimeError(self.name+
  56. " didn't accept a message within one second")
  57.  
  58. def read_players():
  59. communicators = []
  60. for dir in os.listdir(r"bots/"):
  61. try:
  62. file = open("bots/"+dir+"/command.txt", 'r')
  63. except IOError:
  64. continue
  65. command = file.read()
  66. file.close()
  67. communicators.append(Communicator(dir,command))
  68. return communicators
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement