def _getColourData(self, filepath): try: lines = open(filepath).readlines() except IOError: return {} result = {} for line in lines: line = line.strip() if line == '' or line.startswith('#'): continue bits = line.split('=', 1) # Perform basic checks invalid = False if len(bits) != 2: invalid = True else: try: colour = unrepr(bits[1]) if type(colour) is str: colour = colour.strip("'") except: invalid = True else: if colour in list(result.keys()): colour = result[colour] else: if (not isinstance(colour, tuple) or len(colour) < 3 or len(colour) > 4): invalid = True if invalid: log.warning('Invalid colour config line: %r', line) else: result[bits[0].strip()] = colour return result
def fromFile(layoutDatabase, filename): mapDir = getPath(user, 'maps') filename = os.path.join(mapDir, filename) if not os.path.exists(filename): raise IOError("Map could not be loaded; it doesn't exist!") with open(filename, 'r') as f: layoutStr = f.read() return MapLayout.fromDumpedState(layoutDatabase, unrepr(layoutStr))
def datagramReceived(self, datagram, address): ''' A reply to our query has been received. ''' if self._deferred is None: return if datagram.startswith(b'%s:Game:' % (MULTICAST_PROTOCOL_NAME, )): gameInfo = unrepr(datagram[len(b'%s:Game:' % (MULTICAST_PROTOCOL_NAME, )):]) gameAddress = (address[0], gameInfo.pop('port')) self._games.append((gameAddress, gameInfo))
def _loadSettingsFile(self): ''' Loads the data from the settings file and returns it in a dict. ''' filename = self._getSettingsFilename() try: with open(filename, 'r') as f: d = unrepr.unrepr(f.read()) if not isinstance(d, dict): d = {} except IOError: d = {} return d
def __init__(self, filename, *args, **kwargs): super(ReplayPlayer, self).__init__(*args, **kwargs) self.tickPeriod = TICK_PERIOD self.file = open(filename, 'rb') self.finished = False self.loop = WeakLoopingCall(self, 'tick') self.agentIds = [] self.nextAgentId = 0 try: length = struct.unpack('!I', self.file.read(4))[0] except struct.error: raise ReplayFileError('invalid replay format') data = self.file.read(length) self.settings = unrepr(data)
def gotInitClientMsg(self, msg): # Settings from the server. settings = unrepr(msg.settings) # Check that we recognise the server version. svrVersion = settings.get('serverVersion', 'server.v1.0.0+') if svrVersion not in validServerVersions: log.info('Client: bad server version %s', svrVersion) self.settings_deferred.errback(Failure( ConnectionFailed('Incompatible server version.'))) self.transport.abortConnection() return # Tell the client that the connection has been made. self.validated = True self.settings_deferred.callback(settings)
def addLayoutAtFilename(self, filepath): # Remember the filename. self.filename = os.path.split(filepath)[1] # Read the file and create the block f = open(filepath, 'rU') try: contents = f.read() finally: f.close() self.checksum = sha512(contents).hexdigest() try: contentDict = unrepr.unrepr(contents) self.addLayout(filepath, **contentDict) except Exception as e: log.warning(str(e)) return False return True
def addLayoutAtFilename(self, filepath): # Remember the filename. self.filename = os.path.split(filepath)[1] # Read the file and create the block f = open(filepath, 'rb') try: contents = f.read() finally: f.close() self.checksum = sha512(contents).hexdigest() try: contentDict = unrepr.unrepr(contents.decode('utf-8')) except Exception as e: log.warning('Error decoding map block %r: %s: %s', filepath, e.__class__.__name__, e) return False self.addLayout(filepath, **contentDict) return True
def readReplay(fileObject): ''' Returns (settings, messageIterator) where settings is a dict of world settings and messageIterator iterates through the messages in this replay. May raise ReplayFileError if the initial file settings cannot be read. ''' try: length = struct.unpack('!I', fileObject.read(4))[0] data = fileObject.read(length) if len(data) != length: raise ReplayFileError('invalid replay format') decodedData = data.decode('utf-8') except (struct.error, MemoryError, UnicodeDecodeError): raise ReplayFileError('invalid replay format') try: settings = unrepr(decodedData) except Exception: raise ReplayFileError('invalid replay format') return settings, readReplayMessages(fileObject)
def loadNewLayoutFile(self, filename): with open(filename, 'r') as f: data = unrepr.unrepr(f.read()) return maptree.BlockLayout(data)