def read_batchfile(pythonpath, file_ending='.py'):
    """
    This reads the contents of a batch-file.
    Filename is considered to be a python path to a batch file
    relative the directory specified in `settings.py`.

    file_ending specify which batchfile ending should be
    assumed (.ev or .py). The ending should not be included
    in the python path.
    """

    # open the file
    abspaths = []
    for basepath in settings.BASE_BATCHPROCESS_PATHS:
        # note that pypath_to_realpath has already checked the file for existence
        if basepath.startswith("evennia"):
            basepath = basepath.split("evennia", 1)[-1]
        abspaths.extend(utils.pypath_to_realpath("%s.%s" % (basepath, pythonpath), file_ending))
    if not abspaths:
        raise IOError
    text = None
    decoderr = []
    for abspath in abspaths:
        # try different paths, until we get a match
        # we read the file directly into unicode.
        for file_encoding in ENCODINGS:
            # try different encodings, in order
            try:
                with codecs.open(abspath, 'r', encoding=file_encoding) as fobj:
                    text = fobj.read()
            except (ValueError, UnicodeDecodeError), e:
                # this means an encoding error; try another encoding
                decoderr.append(str(e))
                continue
            break
Example #2
0
    def at_start(self):
        """Set up the event system when starting.

        Note that this hook is called every time the server restarts
        (including when it's reloaded).  This hook performs the following
        tasks:

        -   Create temporarily stored events.
        -   Generate locals (individual events' namespace).
        -   Load eventfuncs, including user-defined ones.
        -   Re-schedule tasks that aren't set to fire anymore.
        -   Effectively connect the handler to the main script.

        """
        self.ndb.events = {}
        for typeclass, name, variables, help_text, custom_call, custom_add in EVENTS:
            self.add_event(typeclass, name, variables, help_text, custom_call,
                           custom_add)

        # Generate locals
        self.ndb.current_locals = {}
        self.ndb.fresh_locals = {}
        addresses = ["evennia.contrib.ingame_python.eventfuncs"]
        addresses.extend(
            getattr(settings, "EVENTFUNCS_LOCATIONS", ["world.eventfuncs"]))
        for address in addresses:
            if pypath_to_realpath(address):
                self.ndb.fresh_locals.update(all_from_module(address))

        # Restart the delayed tasks
        now = datetime.now()
        for task_id, definition in tuple(self.db.tasks.items()):
            future, obj, event_name, locals = definition
            seconds = (future - now).total_seconds()
            if seconds < 0:
                seconds = 0

            delay(seconds, complete_task, task_id)

        # Place the script in the CallbackHandler
        from evennia.contrib.ingame_python import typeclasses

        CallbackHandler.script = self
        DefaultObject.callbacks = typeclasses.EventObject.callbacks

        # Create the channel if non-existent
        try:
            self.ndb.channel = ChannelDB.objects.get(db_key="everror")
        except ChannelDB.DoesNotExist:
            self.ndb.channel = create_channel(
                "everror",
                desc="Event errors",
                locks="control:false();listen:perm(Builders);send:false()",
            )
Example #3
0
    def at_start(self):
        """Set up the event system when starting.

        Note that this hook is called every time the server restarts
        (including when it's reloaded).  This hook performs the following
        tasks:

        -   Create temporarily stored events.
        -   Generate locals (individual events' namespace).
        -   Load eventfuncs, including user-defined ones.
        -   Re-schedule tasks that aren't set to fire anymore.
        -   Effectively connect the handler to the main script.

        """
        self.ndb.events = {}
        for typeclass, name, variables, help_text, custom_call, custom_add in EVENTS:
            self.add_event(typeclass, name, variables, help_text, custom_call, custom_add)

        # Generate locals
        self.ndb.current_locals = {}
        self.ndb.fresh_locals = {}
        addresses = ["evennia.contrib.ingame_python.eventfuncs"]
        addresses.extend(getattr(settings, "EVENTFUNCS_LOCATIONS", ["world.eventfuncs"]))
        for address in addresses:
            if pypath_to_realpath(address):
                self.ndb.fresh_locals.update(all_from_module(address))

        # Restart the delayed tasks
        now = datetime.now()
        for task_id, definition in tuple(self.db.tasks.items()):
            future, obj, event_name, locals = definition
            seconds = (future - now).total_seconds()
            if seconds < 0:
                seconds = 0

            delay(seconds, complete_task, task_id)

        # Place the script in the CallbackHandler
        from evennia.contrib.ingame_python import typeclasses
        CallbackHandler.script = self
        DefaultObject.callbacks = typeclasses.EventObject.callbacks

        # Create the channel if non-existent
        try:
            self.ndb.channel = ChannelDB.objects.get(db_key="everror")
        except ChannelDB.DoesNotExist:
            self.ndb.channel = create_channel("everror", desc="Event errors",
                    locks="control:false();listen:perm(Builders);send:false()")
Example #4
0
def read_batchfile(pythonpath, file_ending=".py"):
    """
    This reads the contents of a batch-file.  Filename is considered
    to be a python path to a batch file relative the directory
    specified in `settings.py`.

    file_ending specify which batchfile ending should be assumed (.ev
    or .py). The ending should not be included in the python path.

    Args:
        pythonpath (str): A dot-python path to a file.
        file_ending (str): The file ending of this file (.ev or .py)

    Returns:
        str: The text content of the batch file.

    Raises:
        IOError: If problems reading file.

    """

    # find all possible absolute paths
    abspaths = utils.pypath_to_realpath(pythonpath, file_ending,
                                        settings.BASE_BATCHPROCESS_PATHS)
    if not abspaths:
        raise IOError("Absolute batchcmd paths could not be found.")
    text = None
    decoderr = []
    for abspath in abspaths:
        # try different paths, until we get a match
        # we read the file directly into string.
        for file_encoding in _ENCODINGS:
            # try different encodings, in order
            try:
                with codecs.open(abspath, "r", encoding=file_encoding) as fobj:
                    text = fobj.read()
            except (ValueError, UnicodeDecodeError) as e:
                # this means an encoding error; try another encoding
                decoderr.append(str(e))
                continue
            break
    if not text and decoderr:
        raise UnicodeDecodeError("\n".join(decoderr), bytearray(), 0, 0, "")

    return text
Example #5
0
def read_batchfile(pythonpath, file_ending='.py'):
    """
    This reads the contents of a batch-file.  Filename is considered
    to be a python path to a batch file relative the directory
    specified in `settings.py`.

    file_ending specify which batchfile ending should be assumed (.ev
    or .py). The ending should not be included in the python path.

    Args:
        pythonpath (str): A dot-python path to a file.
        file_ending (str): The file ending of this file (.ev or .py)

    Returns:
        text (str): The text content of the batch file.

    Raises:
        IOError: If problems reading file.

    """

    # find all possible absolute paths
    abspaths = utils.pypath_to_realpath(pythonpath,
                            file_ending, settings.BASE_BATCHPROCESS_PATHS)
    if not abspaths:
        raise IOError
    text = None
    decoderr = []
    for abspath in abspaths:
        # try different paths, until we get a match
        # we read the file directly into unicode.
        for file_encoding in _ENCODINGS:
            # try different encodings, in order
            try:
                with codecs.open(abspath, 'r', encoding=file_encoding) as fobj:
                    text = fobj.read()
            except (ValueError, UnicodeDecodeError) as e:
                # this means an encoding error; try another encoding
                decoderr.append(str(e))
                continue
            break
    if not text and decoderr:
        raise UnicodeDecodeError("\n".join(decoderr))

    return text