Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import subprocess
- import os
- import select
- import time
- class Communicator(object):
- ON_POSIX = 'posix' in sys.builtin_module_names
- WINDOWS = False
- try:
- select.poll()
- from interruptingcow import timeout
- except:
- WINDOWS = True
- pass
- def __init__(self, bot_name, command):
- self.name = bot_name
- self.process = subprocess.Popen(command, stdout=subprocess.PIPE,
- stdin=subprocess.PIPE, bufsize=1,
- close_fds=Communicator.ON_POSIX,
- cwd="bots/"+name+"/")
- if not Communicator.WINDOWS:
- self.pollin = select.poll()
- self.pollin.register(self.process.stdin, select.POLLOUT)
- def get_response(self):
- if Communicator.WINDOWS:
- while True:
- message = self.process.stdout.readline()
- if __debug__:
- print "got message:"+message
- return message
- if __debug__: print "waiting for response from " + self.name
- try:
- with Communicator.timeout(self.time_limit, exception=RuntimeError):
- response = self.process.stdout.readline()
- if __debug__: print "got response from " + \
- self.name + " : " + response.rstrip()
- return response
- except RuntimeError:
- if __debug__: print "gave up on " + self.name
- raise RuntimeError(self.name+
- " didn't produce a response within one second")
- def send_message(self, message):
- if __debug__: print "send message to " + self.name + " : " + message
- if Communicator.WINDOWS:
- self.process.stdin.write(message+"\n")
- self.process.stdin.flush()
- return
- try:
- with Communicator.timeout(self.time_limit, exception=RuntimeError):
- while not self.pollin.poll(0):
- time.sleep(0.1)
- self.process.stdin.write(message+"\n")
- if __debug__: print "sent message to " + self.name
- except RuntimeError:
- if __debug__: print "gave up on " + self.name
- raise RuntimeError(self.name+
- " didn't accept a message within one second")
- def read_players():
- communicators = []
- for dir in os.listdir(r"bots/"):
- try:
- file = open("bots/"+dir+"/command.txt", 'r')
- except IOError:
- continue
- command = file.read()
- file.close()
- communicators.append(Communicator(dir,command))
- return communicators
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement