evennia.utils package¶
This sub-package holds the miscelaneous utilities used by other modules in Evennia. It also holds the idmapper in-memory caching functionality.
Subpackages¶
- evennia.utils.idmapper package
- evennia.utils.tests package
- Subpackages
- Submodules
- evennia.utils.tests.test_ansi module
- evennia.utils.tests.test_batchprocessors module
- evennia.utils.tests.test_create_functions module
- evennia.utils.tests.test_eveditor module
- evennia.utils.tests.test_evform module
- evennia.utils.tests.test_evmenu module
- evennia.utils.tests.test_gametime module
- evennia.utils.tests.test_tagparsing module
- evennia.utils.tests.test_text2html module
- evennia.utils.tests.test_utils module
- evennia.utils.tests.test_validatorfuncs module
Submodules¶
evennia.utils.ansi module¶
ANSI - Gives colour to text.
Use the codes defined in ANSIPARSER in your text to apply colour to text according to the ANSI standard.
Examples
This is |rRed text|n and this is normal again.
Mostly you should not need to call parse_ansi() explicitly; it is run by Evennia just before returning data to/from the user. Depreciated example forms are available by extending the ansi mapping.
-
class
evennia.utils.ansi.ANSIMeta(*args, **kwargs)[source]¶ Bases:
typeMany functions on ANSIString are just light wrappers around the string base class. We apply them here, as part of the classes construction.
-
class
evennia.utils.ansi.ANSIParser[source]¶ Bases:
objectA class that parses ANSI markup to ANSI command sequences
We also allow to escape colour codes by prepending with a for xterm256, an extra | for Merc-style codes
-
ansi_escapes= re.compile('({{|\\\\|\\|\\|)', re.DOTALL)¶
-
ansi_map= [('|n', '\x1b[0m'), ('|/', '\r\n'), ('|-', '\t'), ('|_', ' '), ('|*', '\x1b[7m'), ('|^', '\x1b[5m'), ('|u', '\x1b[4m'), ('|r', '\x1b[1m\x1b[31m'), ('|g', '\x1b[1m\x1b[32m'), ('|y', '\x1b[1m\x1b[33m'), ('|b', '\x1b[1m\x1b[34m'), ('|m', '\x1b[1m\x1b[35m'), ('|c', '\x1b[1m\x1b[36m'), ('|w', '\x1b[1m\x1b[37m'), ('|x', '\x1b[1m\x1b[30m'), ('|R', '\x1b[22m\x1b[31m'), ('|G', '\x1b[22m\x1b[32m'), ('|Y', '\x1b[22m\x1b[33m'), ('|B', '\x1b[22m\x1b[34m'), ('|M', '\x1b[22m\x1b[35m'), ('|C', '\x1b[22m\x1b[36m'), ('|W', '\x1b[22m\x1b[37m'), ('|X', '\x1b[22m\x1b[30m'), ('|h', '\x1b[1m'), ('|H', '\x1b[22m'), ('|!R', '\x1b[31m'), ('|!G', '\x1b[32m'), ('|!Y', '\x1b[33m'), ('|!B', '\x1b[34m'), ('|!M', '\x1b[35m'), ('|!C', '\x1b[36m'), ('|!W', '\x1b[37m'), ('|!X', '\x1b[30m'), ('|[R', '\x1b[41m'), ('|[G', '\x1b[42m'), ('|[Y', '\x1b[43m'), ('|[B', '\x1b[44m'), ('|[M', '\x1b[45m'), ('|[C', '\x1b[46m'), ('|[W', '\x1b[47m'), ('|[X', '\x1b[40m')]¶
-
ansi_map_dict= {'|!B': '\x1b[34m', '|!C': '\x1b[36m', '|!G': '\x1b[32m', '|!M': '\x1b[35m', '|!R': '\x1b[31m', '|!W': '\x1b[37m', '|!X': '\x1b[30m', '|!Y': '\x1b[33m', '|*': '\x1b[7m', '|-': '\t', '|/': '\r\n', '|B': '\x1b[22m\x1b[34m', '|C': '\x1b[22m\x1b[36m', '|G': '\x1b[22m\x1b[32m', '|H': '\x1b[22m', '|M': '\x1b[22m\x1b[35m', '|R': '\x1b[22m\x1b[31m', '|W': '\x1b[22m\x1b[37m', '|X': '\x1b[22m\x1b[30m', '|Y': '\x1b[22m\x1b[33m', '|[B': '\x1b[44m', '|[C': '\x1b[46m', '|[G': '\x1b[42m', '|[M': '\x1b[45m', '|[R': '\x1b[41m', '|[W': '\x1b[47m', '|[X': '\x1b[40m', '|[Y': '\x1b[43m', '|^': '\x1b[5m', '|_': ' ', '|b': '\x1b[1m\x1b[34m', '|c': '\x1b[1m\x1b[36m', '|g': '\x1b[1m\x1b[32m', '|h': '\x1b[1m', '|m': '\x1b[1m\x1b[35m', '|n': '\x1b[0m', '|r': '\x1b[1m\x1b[31m', '|u': '\x1b[4m', '|w': '\x1b[1m\x1b[37m', '|x': '\x1b[1m\x1b[30m', '|y': '\x1b[1m\x1b[33m'}¶
-
ansi_re= '\\033\\[[0-9;]+m'¶
-
ansi_regex= re.compile('\\033\\[[0-9;]+m')¶
-
ansi_sub= re.compile('\\|n|\\|/|\\|\\-|\\|_|\\|\\*|\\|\\^|\\|u|\\|r|\\|g|\\|y|\\|b|\\|m|\\|c|\\|w|\\|x|\\|R|\\|G|\\|Y|\\|B|\\|M|\\|C|\\|W|\\|X|\\|h|\\|H|\\|!R|\\|!G|\\|!Y|\\|!B|\\|!M|\\|!C|\\|!W|\\|!X|\\|\\[R|\\|\\[G|\\|\, re.DOTALL)¶
-
ansi_xterm256_bright_bg_map= [('|[r', '|[500'), ('|[g', '|[050'), ('|[y', '|[550'), ('|[b', '|[005'), ('|[m', '|[505'), ('|[c', '|[055'), ('|[w', '|[555'), ('|[x', '|[222')]¶
-
ansi_xterm256_bright_bg_map_dict= {'|[b': '|[005', '|[c': '|[055', '|[g': '|[050', '|[m': '|[505', '|[r': '|[500', '|[w': '|[555', '|[x': '|[222', '|[y': '|[550'}¶
-
brightbg_sub= re.compile('(?<!\\|)\\|\\[r|(?<!\\|)\\|\\[g|(?<!\\|)\\|\\[y|(?<!\\|)\\|\\[b|(?<!\\|)\\|\\[m|(?<!\\|)\\|\\[c|(?<!\\|)\\|\\[w|(?<!\\|)\\|\\[x', re.DOTALL)¶
-
mxp_re= '\\|lc(.*?)\\|lt(.*?)\\|le'¶
-
mxp_sub= re.compile('\\|lc(.*?)\\|lt(.*?)\\|le', re.DOTALL)¶
-
parse_ansi(string, strip_ansi=False, xterm256=False, mxp=False)[source]¶ Parses a string, subbing color codes according to the stored mapping.
- Parameters
string (str) – The string to parse.
strip_ansi (boolean, optional) – Strip all found ansi markup.
xterm256 (boolean, optional) – If actually using xterm256 or if these values should be converted to 16-color ANSI.
mxp (boolean, optional) – Parse MXP commands in string.
- Returns
The parsed string.
- Return type
string (str)
-
strip_mxp(string)[source]¶ Strips all MXP codes from a string.
- Parameters
string (str) – The string to strip.
- Returns
The processed string.
- Return type
string (str)
-
strip_raw_codes(string)[source]¶ Strips raw ANSI codes from a string.
- Parameters
string (str) – The string to strip.
- Returns
The processed string.
- Return type
string (str)
-
sub_ansi(ansimatch)[source]¶ Replacer used by re.sub to replace ANSI markers with correct ANSI sequences
- Parameters
ansimatch (re.matchobject) – The match.
- Returns
The processed match string.
- Return type
processed (str)
-
sub_brightbg(ansimatch)[source]¶ Replacer used by re.sub to replace ANSI bright background markers with Xterm256 replacement
- Parameters
ansimatch (re.matchobject) – The match.
- Returns
The processed match string.
- Return type
processed (str)
-
sub_xterm256(rgbmatch, use_xterm256=False, color_type='fg')[source]¶ This is a replacer method called by re.sub with the matched tag. It must return the correct ansi sequence.
It checks self.do_xterm256 to determine if conversion to standard ANSI should be done or not.
- Parameters
rgbmatch (re.matchobject) – The match.
use_xterm256 (bool, optional) – Don’t convert 256-colors to 16.
color_type (str) – One of ‘fg’, ‘bg’, ‘gfg’, ‘gbg’.
- Returns
The processed match string.
- Return type
processed (str)
-
xterm256_bg= ['\\|\\[([0-5])([0-5])([0-5])']¶
-
xterm256_bg_sub= re.compile('\\|\\[([0-5])([0-5])([0-5])', re.DOTALL)¶
-
xterm256_fg= ['\\|([0-5])([0-5])([0-5])']¶
-
xterm256_fg_sub= re.compile('\\|([0-5])([0-5])([0-5])', re.DOTALL)¶
-
xterm256_gbg= ['\\|\\[=([a-z])']¶
-
xterm256_gbg_sub= re.compile('\\|\\[=([a-z])', re.DOTALL)¶
-
xterm256_gfg= ['\\|=([a-z])']¶
-
xterm256_gfg_sub= re.compile('\\|=([a-z])', re.DOTALL)¶
-
-
class
evennia.utils.ansi.ANSIString(*_, **kwargs)[source]¶ Bases:
strUnicode-like object that is aware of ANSI codes.
This class can be used nearly identically to strings, in that it will report string length, handle slices, etc, much like a string object would. The methods should be used identically as string methods are.
There is at least one exception to this (and there may be more, though they have not come up yet). When using ‘’.join() or u’’.join() on an ANSIString, color information will get lost. You must use ANSIString(‘’).join() to preserve color information.
This implementation isn’t perfectly clean, as it doesn’t really have an understanding of what the codes mean in order to eliminate redundant characters– though cleaning up the strings might end up being inefficient and slow without some C code when dealing with larger values. Such enhancements could be made as an enhancement to ANSI_PARSER if needed, however.
If one is going to use ANSIString, one should generally avoid converting away from it until one is about to send information on the wire. This is because escape sequences in the string may otherwise already be decoded, and taken literally the second time around.
-
__init__(*_, **kwargs)[source]¶ When the ANSIString is first initialized, a few internal variables have to be set.
The first is the parser. It is possible to replace Evennia’s standard ANSI parser with one of your own syntax if you wish, so long as it implements the same interface.
The second is the _raw_string. This is the original “dumb” string with ansi escapes that ANSIString represents.
The third thing to set is the _clean_string. This is a string that is devoid of all ANSI Escapes.
Finally, _code_indexes and _char_indexes are defined. These are lookup tables for which characters in the raw string are related to ANSI escapes, and which are for the readable text.
-
_filler(char, amount)[source]¶ Generate a line of characters in a more efficient way than just adding ANSIStrings.
-
_get_indexes()[source]¶ Two tables need to be made, one which contains the indexes of all readable characters, and one which contains the indexes of all ANSI escapes. It’s important to remember that ANSI escapes require more that one character at a time, though no readable character needs more than one character, since the string base class abstracts that away from us. However, several readable characters can be placed in a row.
We must use regexes here to figure out where all the escape sequences are hiding in the string. Then we use the ranges of their starts and ends to create a final, comprehensive list of all indexes which are dedicated to code, and all dedicated to text.
It’s possible that only one of these tables is actually needed, the other assumed to be what isn’t in the first.
-
_get_interleving(index)[source]¶ Get the code characters from the given slice end to the next character.
-
static
_shifter(iterable, offset)[source]¶ Takes a list of integers, and produces a new one incrementing all by a number.
-
_slice(slc)[source]¶ This function takes a slice() object.
Slices have to be handled specially. Not only are they able to specify a start and end with [x:y], but many forget that they can also specify an interval with [x:y:z]. As a result, not only do we have to track the ANSI Escapes that have played before the start of the slice, we must also replay any in these intervals, should they exist.
Thankfully, slicing the _char_indexes table gives us the actual indexes that need slicing in the raw string. We can check between those indexes to figure out what escape characters need to be replayed.
-
capitalize(*args, **kwargs)¶
-
center(width, fillchar, _difference)[source]¶ Center some text with some spaces padding both sides.
- Parameters
width (int) – The target width of the output string.
fillchar (str) – A single character string to pad the output string with.
- Returns
A string padded on both ends with fillchar.
- Return type
result (ANSIString)
-
clean()[source]¶ Return a string object without the ANSI escapes.
- Returns
A unicode object with no ANSI escapes.
- Return type
clean_string (str)
-
count(*args, **kwargs)¶
-
decode(*args, **kwargs)¶
-
encode(*args, **kwargs)¶
-
endswith(*args, **kwargs)¶
-
expandtabs(*args, **kwargs)¶
-
find(*args, **kwargs)¶
-
format(*args, **kwargs)¶
-
index(*args, **kwargs)¶
-
isalnum(*args, **kwargs)¶
-
isalpha(*args, **kwargs)¶
-
isdigit(*args, **kwargs)¶
-
islower(*args, **kwargs)¶
-
isspace(*args, **kwargs)¶
-
istitle(*args, **kwargs)¶
-
isupper(*args, **kwargs)¶
-
join(iterable)[source]¶ Joins together strings in an iterable, using this string between each one.
- NOTE: This should always be used for joining strings when ANSIStrings
are involved. Otherwise color information will be discarded by python, due to details in the C implementation of strings.
- Parameters
iterable (list of strings) – A list of strings to join together
- Returns
- A single string with all of the iterable’s
contents concatenated, with this string between each. For example:
ANSIString(‘, ‘).join([‘up’, ‘right’, ‘left’, ‘down’])
- …Would return:
ANSIString(‘up, right, left, down’)
- Return type
result (ANSIString)
-
ljust(width, fillchar, _difference)[source]¶ Left justify some text.
- Parameters
width (int) – The target width of the output string.
fillchar (str) – A single character string to pad the output string with.
- Returns
A string padded on the right with fillchar.
- Return type
result (ANSIString)
-
lower(*args, **kwargs)¶
-
lstrip(chars=None)[source]¶ Strip from the left, taking ANSI markers into account.
- Parameters
chars (str, optional) – A string containing individual characters to strip off of the left end of the string. By default, any blank spaces are trimmed.
- Returns
- A new ANSIString with the left end trimmed of
the relevant characters.
- Return type
result (ANSIString)
-
partition(sep, reverse=False)[source]¶ Splits once into three sections (with the separator being the middle section)
We use the same techniques we used in split() to make sure each are colored.
- Parameters
sep (str) – The separator to split the string on.
reverse (boolean) – Whether to split the string on the last occurrence of the separator rather than the first.
- Returns
- prefix (ANSIString): The part of the string before the
separator
sep (ANSIString): The separator itself postfix (ANSIString): The part of the string after the
separator.
- Return type
result (tuple)
-
raw()[source]¶ Return a string object with the ANSI escapes.
- Returns
A unicode object with the raw ANSI escape sequences.
- Return type
raw (str)
-
re_format= re.compile('(?i)(?P<just>(?P<fill>.)?(?P<align>\\<|\\>|\\=|\\^))?(?P<sign>\\+|\\-| )?(?P<alt>\\#)?(?P<zero>0)?(?P<width>\\d+)?(?P<grouping>\\_|\\,)?(?:\\.(?P<precision>\\d+))?(?P<type>b|c|d|e|E|f|F|g|G|n|o|s|x|X, re.IGNORECASE)¶
-
replace(*args, **kwargs)¶
-
rfind(*args, **kwargs)¶
-
rindex(*args, **kwargs)¶
-
rjust(width, fillchar, _difference)[source]¶ Right justify some text.
- Parameters
width (int) – The target width of the output string.
fillchar (str) – A single character string to pad the output string with.
- Returns
A string padded on the left with fillchar.
- Return type
result (ANSIString)
-
rsplit(by=None, maxsplit=-1)[source]¶ Like split, but starts from the end of the string rather than the beginning.
Stolen from PyPy’s pure Python string implementation, tweaked for ANSIString.
PyPy is distributed under the MIT licence. http://opensource.org/licenses/MIT
- Parameters
by (str) – A string to search for which will be used to split the string. For instance, ‘,’ for ‘Hello,world’ would result in [‘Hello’, ‘world’]
maxsplit (int) – The maximum number of times to split the string. For example, a maxsplit of 2 with a by of ‘,’ on the string ‘Hello,world,test,string’ would result in [‘Hello,world’, ‘test’, ‘string’]
- Returns
- A list of ANSIStrings derived from
this string.
- Return type
result (list of ANSIStrings)
-
rstrip(chars=None)[source]¶ Strip from the right, taking ANSI markers into account.
- Parameters
chars (str, optional) – A string containing individual characters to strip off of the right end of the string. By default, any blank spaces are trimmed.
- Returns
- A new ANSIString with the right end trimmed of
the relevant characters.
- Return type
result (ANSIString)
-
split(by=None, maxsplit=-1)[source]¶ Splits a string based on a separator.
Stolen from PyPy’s pure Python string implementation, tweaked for ANSIString.
PyPy is distributed under the MIT licence. http://opensource.org/licenses/MIT
- Parameters
by (str) – A string to search for which will be used to split the string. For instance, ‘,’ for ‘Hello,world’ would result in [‘Hello’, ‘world’]
maxsplit (int) – The maximum number of times to split the string. For example, a maxsplit of 2 with a by of ‘,’ on the string ‘Hello,world,test,string’ would result in [‘Hello’, ‘world’, ‘test,string’]
- Returns
- A list of ANSIStrings derived from
this string.
- Return type
result (list of ANSIStrings)
-
startswith(*args, **kwargs)¶
-
strip(chars=None)[source]¶ Strip from both ends, taking ANSI markers into account.
- Parameters
chars (str, optional) – A string containing individual characters to strip off of both ends of the string. By default, any blank spaces are trimmed.
- Returns
- A new ANSIString with the ends trimmed of the
relevant characters.
- Return type
result (ANSIString)
-
swapcase(*args, **kwargs)¶
-
translate(*args, **kwargs)¶
-
upper(*args, **kwargs)¶
-
-
evennia.utils.ansi._on_raw(func_name)[source]¶ Like query_super, but makes the operation run on the raw string.
-
evennia.utils.ansi._query_super(func_name)[source]¶ Have the string class handle this with the cleaned string instead of ANSIString.
-
evennia.utils.ansi._spacing_preflight(func)[source]¶ This wrapper function is used to do some preflight checks on functions used for padding ANSIStrings.
-
evennia.utils.ansi._transform(func_name)[source]¶ Some string functions, like those manipulating capital letters, return a string the same length as the original. This function allows us to do the same, replacing all the non-coded characters with the resulting string.
-
evennia.utils.ansi.parse_ansi(string, strip_ansi=False, parser=<evennia.utils.ansi.ANSIParser object>, xterm256=False, mxp=False)[source]¶ Parses a string, subbing color codes as needed.
- Parameters
string (str) – The string to parse.
strip_ansi (bool, optional) – Strip all ANSI sequences.
parser (ansi.AnsiParser, optional) – A parser instance to use.
xterm256 (bool, optional) – Support xterm256 or not.
mxp (bool, optional) – Support MXP markup or not.
- Returns
The parsed string.
- Return type
string (str)
-
evennia.utils.ansi.raw(string)[source]¶ Escapes a string into a form which won’t be colorized by the ansi parser.
- Returns
The raw, escaped string.
- Return type
string (str)
-
evennia.utils.ansi.strip_ansi(string, parser=<evennia.utils.ansi.ANSIParser object>)[source]¶ Strip all ansi from the string. This handles the Evennia-specific markup.
- Parameters
string (str) – The string to strip.
parser (ansi.AnsiParser, optional) – The parser to use.
- Returns
The stripped string.
- Return type
string (str)
-
evennia.utils.ansi.strip_raw_ansi(string, parser=<evennia.utils.ansi.ANSIParser object>)[source]¶ Remove raw ansi codes from string. This assumes pure ANSI-bytecodes in the string.
- Parameters
string (str) – The string to parse.
parser (bool, optional) – The parser to use.
- Returns
the stripped string.
- Return type
string (str)
evennia.utils.batchprocessors module¶
This module contains the core methods for the Batch-command- and Batch-code-processors respectively. In short, these are two different ways to build a game world using a normal text-editor without having to do so ‘on the fly’ in-game. They also serve as an automatic backup so you can quickly recreate a world also after a server reset. The functions in this module is meant to form the backbone of a system called and accessed through game commands.
The Batch-command processor is the simplest. It simply runs a list of in-game commands in sequence by reading them from a text file. The advantage of this is that the builder only need to remember the normal in-game commands. They are also executing with full permission checks etc, making it relatively safe for builders to use. The drawback is that in-game there is really a builder-character walking around building things, and it can be important to create rooms and objects in the right order, so the character can move between them. Also objects that affects players (such as mobs, dark rooms etc) will affect the building character too, requiring extra care to turn off/on.
The Batch-code processor is a more advanced system that accepts full Python code, executing in chunks. The advantage of this is much more power; practically anything imaginable can be coded and handled using the batch-code processor. There is no in-game character that moves and that can be affected by what is being built - the database is populated on the fly. The drawback is safety and entry threshold - the code is executed as would any server code, without mud-specific permission-checks, and you have full access to modifying objects etc. You also need to know Python and Evennia’s API. Hence it’s recommended that the batch-code processor is limited only to superusers or highly trusted staff.
Batch-command processor file syntax
The batch-command processor accepts ‘batchcommand files’ e.g batch.ev, containing a sequence of valid Evennia commands in a simple format. The engine runs each command in sequence, as if they had been run at the game prompt.
Each Evennia command must be delimited by a line comment to mark its end.
``` #INSERT path.batchcmdfile - this as the first entry on a line will
import and run a batch.ev file in this position, as if it was written in this file.
This way entire game worlds can be created and planned offline; it is especially useful in order to create long room descriptions where a real offline text editor is often much better than any online text editor or prompt.
Example of batch.ev file:¶
``` # batch file # all lines starting with # are comments; they also indicate # that a command definition is over.
@create box
# this comment ends the @create command.
@set box/desc = A large box.
Inside are some scattered piles of clothing.
It seems the bottom of the box is a bit loose.
# Again, this comment indicates the @set command is over. Note how # the description could be freely added. Excess whitespace on a line # is ignored. An empty line in the command definition is parsed as a
# (so two empty lines becomes a new paragraph).
@teleport #221
# (Assuming #221 is a warehouse or something.) # (remember, this comment ends the @teleport command! Don’f forget it)
# Example of importing another file at this point. #IMPORT examples.batch
@drop box
# Done, the box is in the warehouse! (this last comment is not necessary to # close the @drop command since it’s the end of the file) ```
An example batch file is contrib/examples/batch_example.ev.
Batch-code processor file syntax
The Batch-code processor accepts full python modules (e.g. batch.py) that looks identical to normal Python files. The difference from importing and running any Python module is that the batch-code module is loaded as a file and executed directly, so changes to the file will apply immediately without a server @reload.
Optionally, one can add some special commented tokens to split the execution of the code for the benefit of the batchprocessor’s interactive- and debug-modes. This allows to conveniently step through the code and re-run sections of it easily during development.
Code blocks are marked by commented tokens alone on a line:
- #HEADER - This denotes code that should be pasted at the top of all
other code. Multiple HEADER statements - regardless of where it exists in the file - is the same as one big block. Observe that changes to variables made in one block is not preserved between blocks!
- #CODE - This designates a code block that will be executed like a
stand-alone piece of code together with any HEADER(s) defined. It is mainly used as a way to mark stop points for the interactive mode of the batchprocessor. If no CODE block is defined in the module, the entire module (including HEADERS) is assumed to be a CODE block.
- #INSERT path.filename - This imports another batch_code.py file and
runs it in the given position. The inserted file will retain its own HEADERs which will not be mixed with the headers of this file.
Importing works as normal. The following variables are automatically made available in the script namespace.
caller - The object executing the batchscript
- DEBUG - This is a boolean marking if the batchprocessor is running
in debug mode. It can be checked to e.g. delete created objects when running a CODE block multiple times during testing. (avoids creating a slew of same-named db objects)
Example batch.py file¶
``` #HEADER
from django.conf import settings from evennia.utils import create from types import basetypes
GOLD = 10
#CODE
obj = create.create_object(basetypes.Object) obj2 = create.create_object(basetypes.Object) obj.location = caller.location obj.db.gold = GOLD caller.msg(“The object was created!”)
- if DEBUG:
obj.delete() obj2.delete()
#INSERT another_batch_file
#CODE
script = create.create_script() ```
-
class
evennia.utils.batchprocessors.BatchCodeProcessor[source]¶ Bases:
objectThis implements a batch-code processor
-
code_exec(code, extra_environ=None, debug=False)[source]¶ Execute a single code block, including imports and appending global vars.
- Parameters
code (str) – Code to run.
extra_environ (dict) – Environment variables to run with code.
debug (bool, optional) – Set the DEBUG variable in the execution namespace.
- Returns
An error code or None (ok).
- Return type
err (str or None)
-
parse_file(pythonpath)[source]¶ This parses the lines of a batchfile according to the following rules:
- Parameters
pythonpath (str) – The dot-python path to the file.
- Returns
- A list of all #CODE blocks, each with
prepended #HEADER data. If no #CODE blocks were found, this will be a list of one element.
- Return type
codeblocks (list)
Notes
- Code before a #CODE/HEADER block are considered part of
the first code/header block or is the ONLY block if no #CODE/HEADER blocks are defined.
Lines starting with #HEADER starts a header block (ends other blocks)
Lines starting with #CODE begins a code block (ends other blocks)
Lines starting with #INSERT are on form #INSERT filename. Code from this file are processed with their headers separately before being inserted at the point of the #INSERT.
Code after the last block is considered part of the last header/code block
-
-
class
evennia.utils.batchprocessors.BatchCommandProcessor[source]¶ Bases:
objectThis class implements a batch-command processor.
-
parse_file(pythonpath)[source]¶ This parses the lines of a batchfile according to the following rules:
- # at the beginning of a line marks the end of the command before
it. It is also a comment and any number of # can exist on subsequent lines (but not inside comments).
#INSERT at the beginning of a line imports another batch-cmd file file and pastes it into the batch file as if it was written there.
Commands are placed alone at the beginning of a line and their arguments are considered to be everything following (on any number of lines) until the next comment line beginning with #.
Newlines are ignored in command definitions
A completely empty line in a command line definition is condered a newline (so two empty lines is a paragraph).
Excess spaces and indents inside arguments are stripped.
-
-
evennia.utils.batchprocessors.read_batchfile(pythonpath, file_ending='.py')[source]¶ 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.
- Parameters
pythonpath (str) – A dot-python path to a file.
file_ending (str) – The file ending of this file (.ev or .py)
- Returns
The text content of the batch file.
- Return type
text (str)
- Raises
IOError – If problems reading file.
evennia.utils.containers module¶
Containers
Containers are storage classes usually initialized from a setting. They represent Singletons and acts as a convenient place to find resources ( available as properties on the singleton)
evennia.GLOBAL_SCRIPTS evennia.OPTION_CLASSES
-
class
evennia.utils.containers.Container[source]¶ Bases:
objectBase container class. A container is simply a storage object whose properties can be acquired as a property on it. This is generally considered a read-only affair.
The container is initialized by a list of modules containing callables.
-
all()[source]¶ Get all stored data
- Returns
All global script objects stored on the container.
- Return type
scripts (list)
-
get(key, default=None)[source]¶ Retrive data by key (in case of not knowing it beforehand).
- Parameters
key (str) – The name of the script.
default (any, optional) – Value to return if key is not found.
- Returns
The data loaded on this container.
- Return type
any (any)
-
load_data()[source]¶ Delayed import to avoid eventual circular imports from inside the storage modules.
-
storage_modules= []¶
-
-
class
evennia.utils.containers.GlobalScriptContainer[source]¶ Bases:
evennia.utils.containers.ContainerSimple Handler object loaded by the Evennia API to contain and manage a game’s Global Scripts. This will list global Scripts created on their own but will also auto-(re)create scripts defined in settings.GLOBAL_SCRIPTS.
Example
import evennia evennia.GLOBAL_SCRIPTS.scriptname
Note
This does not use much of the BaseContainer since it’s not loading callables from settings but a custom dict of tuples.
-
__init__()[source]¶ Note: We must delay loading of typeclasses since this module may get initialized before Scripts are actually initialized.
-
all()[source]¶ Get all global scripts. Note that this will not auto-start scripts defined in settings.
- Returns
All global script objects stored on the container.
- Return type
scripts (list)
-
get(key, default=None)[source]¶ Retrive data by key (in case of not knowing it beforehand). Any scripts that are in settings.GLOBAL_SCRIPTS that are not found will be recreated on-demand.
- Parameters
key (str) – The name of the script.
default (any, optional) – Value to return if key is not found at all on this container (i.e it cannot be loaded at all).
- Returns
The data loaded on this container.
- Return type
any (any)
-
-
class
evennia.utils.containers.OptionContainer[source]¶ Bases:
evennia.utils.containers.ContainerLoads and stores the final list of OPTION CLASSES.
Can access these as properties or dictionary-contents.
-
storage_modules= ['evennia.utils.optionclasses']¶
-
evennia.utils.create module¶
This module gathers all the essential database-creation functions for the game engine’s various object types.
Only objects created ‘stand-alone’ are in here, e.g. object Attributes are always created directly through their respective objects.
Each creation_* function also has an alias named for the entity being created, such as create_object() and object(). This is for consistency with the utils.search module and allows you to do the shorter “create.object()”.
The respective object managers hold more methods for manipulating and searching objects already existing in the database.
- Models covered:
Objects Scripts Help Message Channel Accounts
-
evennia.utils.create.create_object(typeclass=None, key=None, location=None, home=None, permissions=None, locks=None, aliases=None, tags=None, destination=None, report_to=None, nohome=False, attributes=None, nattributes=None)[source]¶ Create a new in-game object.
- Kwargs:
typeclass (class or str): Class or python path to a typeclass. key (str): Name of the new object. If not set, a name of
#dbref will be set.
- home (Object or str): Obj or #dbref to use as the object’s
home location.
permissions (list): A list of permission strings or tuples (permstring, category). locks (str): one or more lockstrings, separated by semicolons. aliases (list): A list of alternative keys or tuples (aliasstring, category). tags (list): List of tag keys or tuples (tagkey, category) or (tagkey, category, data). destination (Object or str): Obj or #dbref to use as an Exit’s
target.
report_to (Object): The object to return error messages to. nohome (bool): This allows the creation of objects without a
default home location; only used when creating the default location itself or during unittests.
- attributes (list): Tuples on the form (key, value) or (key, value, category),
- (key, value, lockstring) or (key, value, lockstring, default_access).
to set as Attributes on the new object.
- nattributes (list): Non-persistent tuples on the form (key, value). Note that
adding this rarely makes sense since this data will not survive a reload.
- Returns
A newly created object of the given typeclass.
- Return type
object (Object)
- Raises
ObjectDB.DoesNotExist – If trying to create an Object with location or home that can’t be found.
-
evennia.utils.create.create_script(typeclass=None, key=None, obj=None, account=None, locks=None, interval=None, start_delay=None, repeats=None, persistent=None, autostart=True, report_to=None, desc=None, tags=None, attributes=None)[source]¶ Create a new script. All scripts are a combination of a database object that communicates with the database, and an typeclass that ‘decorates’ the database object into being different types of scripts. It’s behaviour is similar to the game objects except scripts has a time component and are more limited in scope.
- Kwargs:
typeclass (class or str): Class or python path to a typeclass. key (str): Name of the new object. If not set, a name of
#dbref will be set.
- obj (Object): The entity on which this Script sits. If this
is None, we are creating a “global” script.
- account (Account): The account on which this Script sits. It is
exclusiv to obj.
locks (str): one or more lockstrings, separated by semicolons. interval (int): The triggering interval for this Script, in
seconds. If unset, the Script will not have a timing component.
- start_delay (bool): If True, will wait interval seconds
before triggering the first time.
- repeats (int): The number of times to trigger before stopping.
If unset, will repeat indefinitely.
- persistent (bool): If this Script survives a server shutdown
or not (all Scripts will survive a reload).
- autostart (bool): If this Script will start immediately when
created or if the start method must be called explicitly.
report_to (Object): The object to return error messages to. desc (str): Optional description of script tags (list): List of tags or tuples (tag, category). attributes (list): List if tuples (key, value) or (key, value, category)
(key, value, lockstring) or (key, value, lockstring, default_access).
- Returns
An instance of the script created
- Return type
script (obj)
See evennia.scripts.manager for methods to manipulate existing scripts in the database.
-
evennia.utils.create.create_help_entry(key, entrytext, category='General', locks=None, aliases=None)[source]¶ Create a static help entry in the help database. Note that Command help entries are dynamic and directly taken from the __doc__ entries of the command. The database-stored help entries are intended for more general help on the game, more extensive info, in-game setting information and so on.
- Parameters
key (str) – The name of the help entry.
entrytext (str) – The body of te help entry
category (str, optional) – The help category of the entry.
locks (str, optional) – A lockstring to restrict access.
aliases (list of str) – List of alternative (likely shorter) keynames.
- Returns
A newly created help entry.
- Return type
help (HelpEntry)
-
evennia.utils.create.create_message(senderobj, message, channels=None, receivers=None, locks=None, header=None)[source]¶ Create a new communication Msg. Msgs represent a unit of database-persistent communication between entites.
- Parameters
senderobj (Object or Account) – The entity sending the Msg.
message (str) – Text with the message. Eventual headers, titles etc should all be included in this text string. Formatting will be retained.
channels (Channel, key or list) – A channel or a list of channels to send to. The channels may be actual channel objects or their unique key strings.
receivers (Object, Account, str or list) – An Account/Object to send to, or a list of them. May be Account objects or accountnames.
locks (str) – Lock definition string.
header (str) – Mime-type or other optional information for the message
Notes
The Comm system is created very open-ended, so it’s fully possible to let a message both go to several channels and to several receivers at the same time, it’s up to the command definitions to limit this as desired.
-
evennia.utils.create.create_channel(key, aliases=None, desc=None, locks=None, keep_log=True, typeclass=None)[source]¶ Create A communication Channel. A Channel serves as a central hub for distributing Msgs to groups of people without specifying the receivers explicitly. Instead accounts may ‘connect’ to the channel and follow the flow of messages. By default the channel allows access to all old messages, but this can be turned off with the keep_log switch.
- Parameters
key (str) – This must be unique.
- Kwargs:
aliases (list of str): List of alternative (likely shorter) keynames. desc (str): A description of the channel, for use in listings. locks (str): Lockstring. keep_log (bool): Log channel throughput. typeclass (str or class): The typeclass of the Channel (not
often used).
- Returns
A newly created channel.
- Return type
channel (Channel)
-
evennia.utils.create.create_account(key, email, password, typeclass=None, is_superuser=False, locks=None, permissions=None, tags=None, attributes=None, report_to=None)[source]¶ This creates a new account.
- Parameters
key (str) – The account’s name. This should be unique.
email (str or None) – Email on valid addr@addr.domain form. If the empty string, will be set to None.
password (str) – Password in cleartext.
- Kwargs:
typeclass (str): The typeclass to use for the account. is_superuser (bool): Wether or not this account is to be a superuser locks (str): Lockstring. permission (list): List of permission strings. tags (list): List of Tags on form (key, category[, data]) attributes (list): List of Attributes on form
(key, value [, category, [,lockstring [, default_pass]]])
- report_to (Object): An object with a msg() method to report
errors to. If not given, errors will be logged.
- Returns
The newly created Account.
- Return type
Account
- Raises
ValueError – If key already exists in database.
Notes
Usually only the server admin should need to be superuser, all other access levels can be handled with more fine-grained permissions or groups. A superuser bypasses all lock checking operations and is thus not suitable for play-testing the game.
evennia.utils.dbserialize module¶
This module handles serialization of arbitrary python structural data, intended primarily to be stored in the database. It also supports storing Django model instances (which plain pickle cannot do).
This serialization is used internally by the server, notably for storing data in Attributes and for piping data to process pools.
The purpose of dbserialize is to handle all forms of data. For well-structured non-arbitrary exchange, such as communicating with a rich web client, a simpler JSON serialization makes more sense.
This module also implements the SaverList, SaverDict and SaverSet classes. These are iterables that track their position in a nested structure and makes sure to send updates up to their root. This is used by Attributes - without it, one would not be able to update mutables in-situ, e.g obj.db.mynestedlist[3][5] = 3 would never be saved and be out of sync with the database.
-
evennia.utils.dbserialize.to_pickle(data)[source]¶ This prepares data on arbitrary form to be pickled. It handles any nested structure and returns data on a form that is safe to pickle (including having converted any database models to their internal representation). We also convert any Saver*-type objects back to their normal representations, they are not pickle-safe.
- Parameters
data (any) – Data to pickle.
- Returns
Pickled data.
- Return type
data (any)
-
evennia.utils.dbserialize.from_pickle(data, db_obj=None)[source]¶ This should be fed a just de-pickled data object. It will be converted back to a form that may contain database objects again. Note that if a database object was removed (or changed in-place) in the database, None will be returned.
- Args_
data (any): Pickled data to unpickle. db_obj (Atribute, any): This is the model instance (normally
an Attribute) that _Saver*-type iterables (_SaverList etc) will save to when they update. It must have a ‘value’ property that saves assigned data to the database. Skip if not serializing onto a given object. If db_obj is given, this function will convert lists, dicts and sets to their _SaverList, _SaverDict and _SaverSet counterparts.
- Returns
Unpickled data.
- Return type
data (any)
evennia.utils.eveditor module¶
EvEditor (Evennia Line Editor)
This implements an advanced line editor for editing longer texts in-game. The editor mimics the command mechanisms of the “VI” editor (a famous line-by-line editor) as far as reasonable.
Features of the editor:
undo/redo.
edit/replace on any line of the buffer.
search&replace text anywhere in buffer.
formatting of buffer, or selection, to certain width + indentations.
allow to echo the input or not, depending on your client.
To use the editor, just import EvEditor from this module and initialize it:
from evennia.utils.eveditor import EvEditor
EvEditor(caller, loadfunc=None, savefunc=None, quitfunc=None, key=””, persistent=True)
caller is the user of the editor, the one to see all feedback.
loadfunc(caller) is called when the editor is first launched; the return from this function is loaded as the starting buffer in the editor.
safefunc(caller, buffer) is called with the current buffer when saving in the editor. The function should return True/False depending on if the saving was successful or not.
quitfunc(caller) is called when the editor exits. If this is given, no automatic quit messages will be given.
key is an optional identifier for the editing session, to be displayed in the editor.
persistent means the editor state will be saved to the database making it survive a server reload. Note that using this mode, the load- save- and quit-funcs must all be possible to pickle - notable unusable callables are class methods and functions defined inside other functions. With persistent=False, no such restriction exists.
code set to True activates features on the EvEditor to enter Python code.
In addition, the EvEditor can be used to enter Python source code, and offers basic handling of indentation.
-
class
evennia.utils.eveditor.CmdEditorBase(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandBase parent for editor commands
-
_keyaliases= ('command',)¶
-
_matchset= {'command'}¶
-
aliases= []¶
-
editor= None¶
-
help_category= 'general'¶
-
help_entry= 'LineEditor'¶
-
key= 'command'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
parse()[source]¶ Handles pre-parsing
- Editor commands are on the form
:cmd [li] [w] [txt]
- Where all arguments are optional.
- li - line number (int), starting from 1. This could also
be a range given as <l>:<l>.
w - word(s) (string), could be encased in quotes. txt - extra text (string), could be encased in quotes.
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'command', 'tags': '', 'text': '\n Base parent for editor commands\n '}¶
-
-
class
evennia.utils.eveditor.CmdEditorGroup(**kwargs)[source]¶ Bases:
evennia.utils.eveditor.CmdEditorBaseCommands for the editor
-
_keyaliases= (':q', ':i', ':h', ':I', ':s', '::', ':dd', ':dw', ':j', ':::', ':DD', ':S', ':UU', ':r', ':x', ':p', ':=', ':fi', ':', ':A', ':u', ':<', ':editor_command_group', ':uu', ':>', ':q!', ':wq', ':echo', ':y', ':fd', ':!', ':f', ':w')¶
-
_matchset= {':', ':!', '::', ':::', ':<', ':=', ':>', ':A', ':DD', ':I', ':S', ':UU', ':dd', ':dw', ':echo', ':editor_command_group', ':f', ':fd', ':fi', ':h', ':i', ':j', ':p', ':q', ':q!', ':r', ':s', ':u', ':uu', ':w', ':wq', ':x', ':y'}¶
-
aliases= [':q', ':i', ':h', ':I', ':s', '::', ':dd', ':dw', ':j', ':::', ':DD', ':S', ':UU', ':r', ':x', ':p', ':=', ':fi', ':', ':A', ':u', ':<', ':uu', ':>', ':q!', ':wq', ':echo', ':y', ':fd', ':!', ':f', ':w']¶
-
arg_regex= re.compile('\\s.*?|$', re.IGNORECASE)¶
-
func()[source]¶ This command handles all the in-editor :-style commands. Since each command is small and very limited, this makes for a more efficient presentation.
-
help_category= 'general'¶
-
key= ':editor_command_group'¶
-
lock_storage= 'cmd:all()'¶
-
search_index_entry= {'aliases': ':q :i :h :I :s :: :dd :dw :j ::: :DD :S :UU :r :x :p := :fi : :A :u :< :uu :> :q! :wq :echo :y :fd :! :f :w', 'category': 'general', 'key': ':editor_command_group', 'tags': '', 'text': '\n Commands for the editor\n '}¶
-
-
class
evennia.utils.eveditor.CmdLineInput(**kwargs)[source]¶ Bases:
evennia.utils.eveditor.CmdEditorBaseNo command match - Inputs line of text into buffer.
-
_keyaliases= ('__noinput_command', '__nomatch_command')¶
-
_matchset= {'__noinput_command', '__nomatch_command'}¶
-
aliases= ['__noinput_command']¶
-
func()[source]¶ Adds the line without any formatting changes.
If the editor handles code, it might add automatic indentation.
-
help_category= 'general'¶
-
key= '__nomatch_command'¶
-
lock_storage= 'cmd:all()'¶
-
search_index_entry= {'aliases': '__noinput_command', 'category': 'general', 'key': '__nomatch_command', 'tags': '', 'text': '\n No command match - Inputs line of text into buffer.\n '}¶
-
-
class
evennia.utils.eveditor.CmdSaveYesNo(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandSave the editor state on quit. This catches nomatches (defaults to Yes), and avoid saves only if command was given specifically as “no” or “n”.
-
_keyaliases= ('__noinput_command', '__nomatch_command')¶
-
_matchset= {'__noinput_command', '__nomatch_command'}¶
-
aliases= ['__noinput_command']¶
-
help_category= 'general'¶
-
help_cateogory= 'LineEditor'¶
-
key= '__nomatch_command'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '__noinput_command', 'category': 'general', 'key': '__nomatch_command', 'tags': '', 'text': '\n Save the editor state on quit. This catches\n nomatches (defaults to Yes), and avoid saves only if\n command was given specifically as "no" or "n".\n '}¶
-
-
class
evennia.utils.eveditor.EvEditor(caller, loadfunc=None, savefunc=None, quitfunc=None, key='', persistent=False, codefunc=False)[source]¶ Bases:
objectThis defines a line editor object. It creates all relevant commands and tracks the current state of the buffer. It also cleans up after itself.
-
__init__(caller, loadfunc=None, savefunc=None, quitfunc=None, key='', persistent=False, codefunc=False)[source]¶ Launches a full in-game line editor, mimicking the functionality of VIM.
- Parameters
caller (Object) – Who is using the editor.
loadfunc (callable, optional) – This will be called as loadfunc(caller) when the editor is first started. Its return will be used as the editor’s starting buffer.
savefunc (callable, optional) – This will be called as savefunc(caller, buffer) when the save-command is given and is used to actually determine where/how result is saved. It should return True if save was successful and also handle any feedback to the user.
quitfunc (callable, optional) – This will optionally be called as quitfunc(caller) when the editor is exited. If defined, it should handle all wanted feedback to the user.
quitfunc_args (tuple, optional) – Optional tuple of arguments to supply to quitfunc.
key (str, optional) – An optional key for naming this session and make it unique from other editing sessions.
persistent (bool, optional) – Make the editor survive a reboot. Note that if this is set, all callables must be possible to pickle
codefunc (bool, optional) – If given, will run the editor in code mode. This will be called as codefunc(caller, buf).
Notes
In persistent mode, all the input callables (savefunc etc) must be possible to be pickled, this excludes e.g. callables that are class methods or functions defined dynamically or as part of another function. In non-persistent mode no such restrictions exist.
-
display_buffer(buf=None, offset=0, linenums=True, options={'raw': False})[source]¶ This displays the line editor buffer, or selected parts of it.
- Parameters
buf (str, optional) – The buffer or part of buffer to display.
offset (int, optional) – If buf is set and is not the full buffer, offset should define the actual starting line number, to get the linenum display right.
linenums (bool, optional) – Show line numbers in buffer.
options – raw (bool, optional): Tell protocol to not parse formatting information.
-
-
class
evennia.utils.eveditor.EvEditorCmdSet(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.cmdset.CmdSetCmdSet for the editor commands
-
at_cmdset_creation()[source]¶ Hook method - this should be overloaded in the inheriting class, and should take care of populating the cmdset by use of self.add().
-
key= 'editorcmdset'¶
-
mergetype= 'Replace'¶
-
path= 'evennia.utils.eveditor.EvEditorCmdSet'¶
-
evennia.utils.evform module¶
EvForm - a way to create advanced ASCII forms
This is intended for creating advanced ASCII game forms, such as a large pretty character sheet or info document.
The system works on the basis of a readin template that is given in a separate Python file imported into the handler. This file contains some optional settings and a string mapping out the form. The template has markers in it to denounce fields to fill. The markers map the absolute size of the field and will be filled with an evtable.EvCell object when displaying the form.
Example of input file testform.py:
```python FORMCHAR = “x” TABLECHAR = “c”
FORM = ‘’’ .————————————————. | | | Name: xxxxx1xxxxx Player: xxxxxxx2xxxxxxx | | xxxxxxxxxxx | | |
>———————————————-<
The first line of the FORM string is ignored. The forms and table markers must mark out complete, unbroken rectangles, each containing one embedded single-character identifier (so the smallest element possible is a 3-character wide form). The identifier can be any character except for the FORM_CHAR and TABLE_CHAR and some of the common ASCII-art elements, like space, _ | * etc (see INVALID_FORMCHARS in this module). Form Rectangles can have any size, but must be separated from each other by at least one other character’s width.
Use as follows:
- ```python
from evennia import EvForm, EvTable
# create a new form from the template form = EvForm(“path/to/testform.py”)
- (MudForm can also take a dictionary holding
the required keys FORMCHAR, TABLECHAR and FORM)
# add data to each tagged form cell form.map(cells={1: “Tom the Bouncer”,
2: “Griatch”, 3: “A sturdy fellow”, 4: 12, 5: 10, 6: 5, 7: 18, 8: 10, 9: 3})
# create the EvTables tableA = EvTable(“HP”,”MV”,”MP”,
- tableB = EvTable(“Skill”, “Value”, “Exp”,
- table=[[“Shooting”, “Herbalism”, “Smithing”],
[12,14,9],[“550/1200”, “990/1400”, “205/900”]],
border=”incols”)
# add the tables to the proper ids in the form form.map(tables={“A”: tableA,
“B”: tableB})
print(form)
This produces the following result:
``` .————————————————. | | | Name: Tom the Player: Griatch | | Bouncer | | |
>———————————————-<
The marked forms have been replaced with EvCells of text and with EvTables. The form can be updated by simply re-applying form.map() with the updated data.
When working with the template ASCII file, you can use form.reload() to re-read the template and re-apply all existing mappings.
Each component is restrained to the width and height specified by the template, so it will resize to fit (or crop text if the area is too small for it). If you try to fit a table into an area it cannot fit into (when including its borders and at least one line of text), the form will raise an error.
-
class
evennia.utils.evform.EvForm(filename=None, cells=None, tables=None, form=None, **kwargs)[source]¶ Bases:
objectThis object is instantiated with a text file and parses it for rectangular form fields. It can then be fed a mapping so as to populate the fields with fixed-width EvCell or Tables.
-
__init__(filename=None, cells=None, tables=None, form=None, **kwargs)[source]¶ Initiate the form
- Kwargs:
filename (str): Path to template file. cells (dict): A dictionary mapping of {id:text} tables (dict): A dictionary mapping of {id:EvTable}. form (dict): A dictionary of {“FORMCHAR”:char,
“TABLECHAR”:char, “FORM”:templatestring}
if this is given, filename is not read.
Notes
Other kwargs are fed as options to the EvCells and EvTables (see evtable.EvCell and evtable.EvTable for more info).
-
_parse_rectangles(cellchar, tablechar, form, **kwargs)[source]¶ Parse a form for rectangular formfields identified by formchar enclosing an identifier.
-
evennia.utils.evmore module¶
EvMore - pager mechanism
This is a pager for displaying long texts and allows stepping up and down in the text (the name comes from the traditional ‘more’ unix command).
To use, simply pass the text through the EvMore object:
from evennia.utils.evmore import EvMore
text = some_long_text_output() EvMore(caller, text, always_page=False, session=None, justify_kwargs=None, **kwargs)
One can also use the convenience function msg from this module:
from evennia.utils import evmore
text = some_long_text_output() evmore.msg(caller, text, always_page=False, session=None, justify_kwargs=None, **kwargs)
Where always_page decides if the pager is used also if the text is not long enough to need to scroll, session is used to determine which session to relay to and justify_kwargs are kwargs to pass to utils.utils.justify in order to change the formatting of the text. The remaining **kwargs will be passed on to the caller.msg() construct every time the page is updated.
-
class
evennia.utils.evmore.CmdMore(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandManipulate the text paging
-
_keyaliases= ('a', 'e', 'abort', '__noinput_command', 'back', 'end', 'next', 'q', 'n', 'b', 'top', 't', 'quit')¶
-
_matchset= {'__noinput_command', 'a', 'abort', 'b', 'back', 'e', 'end', 'n', 'next', 'q', 'quit', 't', 'top'}¶
-
aliases= ['a', 'e', 'abort', 'back', 'end', 'next', 'q', 'n', 'b', 'top', 't', 'quit']¶
-
auto_help= False¶
-
help_category= 'general'¶
-
key= '__noinput_command'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': 'a e abort back end next q n b top t quit', 'category': 'general', 'key': '__noinput_command', 'tags': '', 'text': '\n Manipulate the text paging\n '}¶
-
-
class
evennia.utils.evmore.CmdMoreLook(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandOverride look to display window and prevent OOCLook from firing
-
_keyaliases= ('look', 'l')¶
-
_matchset= {'l', 'look'}¶
-
aliases= ['l']¶
-
auto_help= False¶
-
help_category= 'general'¶
-
key= 'look'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': 'l', 'category': 'general', 'key': 'look', 'tags': '', 'text': '\n Override look to display window and prevent OOCLook from firing\n '}¶
-
-
class
evennia.utils.evmore.CmdSetMore(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.cmdset.CmdSetStores the more command
-
at_cmdset_creation()[source]¶ Hook method - this should be overloaded in the inheriting class, and should take care of populating the cmdset by use of self.add().
-
key= 'more_commands'¶
-
path= 'evennia.utils.evmore.CmdSetMore'¶
-
priority= 110¶
-
-
class
evennia.utils.evmore.EvMore(caller, text, always_page=False, session=None, justify=False, justify_kwargs=None, exit_on_lastpage=False, exit_cmd=None, page_formatter=<class 'str'>, **kwargs)[source]¶ Bases:
objectThe main pager object
-
__init__(caller, text, always_page=False, session=None, justify=False, justify_kwargs=None, exit_on_lastpage=False, exit_cmd=None, page_formatter=<class 'str'>, **kwargs)[source]¶ Initialization of the text handler.
- Args:
caller (Object or Account): Entity reading the text. text (str, EvTable or iterator): The text or data to put under paging.
- If a string, paginage normally. If this text contains
one or more `
- ` format symbol, automatic pagination and justification
are force-disabled and page-breaks will only happen after each `
- `.
- If EvTable, the EvTable will be paginated with the same
setting on each page if it is too long. The table decorations will be considered in the size of the page.
- Otherwise text is converted to an iterator, where each step is
expected to be a line in the final display. Each line will be run through iter_callable.
- always_page (bool, optional): If False, the
pager will only kick in if text is too big to fit the screen.
- session (Session, optional): If given, this session will be used
to determine the screen width and will receive all output.
- justify (bool, optional): If set, auto-justify long lines. This must be turned
off for fixed-width or formatted output, like tables. It’s force-disabled if text is an EvTable.
- justify_kwargs (dict, optional): Keywords for the justifiy function. Used only
if justify is True. If this is not set, default arguments will be used.
- exit_on_lastpage (bool, optional): If reaching the last page without the
page being completely filled, exit pager immediately. If unset, another move forward is required to exit. If set, the pager exit message will not be shown.
- exit_cmd (str, optional): If given, this command-string will be executed on
the caller when the more page exits. Note that this will be using whatever cmdset the user had before the evmore pager was activated (so none of the evmore commands will be available when this is run).
- page_formatter (callable, optional): If given, this function will be passed the
contents of each extracted page. This is useful when paginating data consisting something other than a string or a list of strings. Especially queryset data is likely to always need this argument specified. Note however, that all size calculations assume this function to return one single line per element on the page!
kwargs (any, optional): These will be passed on to the caller.msg method.
- Examples:
super_long_text = ” … ” EvMore(caller, super_long_text)
from django.core.paginator import Paginator query = ObjectDB.objects.all() pages = Paginator(query, 10) # 10 objs per page EvMore(caller, pages) # will repr() each object per line, 10 to a page
multi_page_table = [ [[..],[..]], …] EvMore(caller, multi_page_table, use_evtable=True,
evtable_args=(“Header1”, “Header2”), evtable_kwargs={“align”: “r”, “border”: “tablecols”})
-
format_page(page)[source]¶ Page formatter. Uses the page_formatter callable by default. This allows to easier override the class if needed.
-
init_f_str(text)[source]¶ The input contains
markers. We use to indicate the user wants to
enforce their line breaks on their own. If so, we do no automatic line-breaking/justification at all.
-
init_iterable(inp)[source]¶ The input is something other than a string - convert to iterable of strings
-
-
evennia.utils.evmore.msg(caller, text='', always_page=False, session=None, justify=False, justify_kwargs=None, exit_on_lastpage=True, **kwargs)[source]¶ EvMore-supported version of msg, mimicking the normal msg method.
- Args:
caller (Object or Account): Entity reading the text. text (str, EvTable or iterator): The text or data to put under paging.
If a string, paginage normally. If this text contains one or more `
- ` format symbol, automatic pagination is disabled
and page-breaks will only happen after each `
- `.
- If EvTable, the EvTable will be paginated with the same
setting on each page if it is too long. The table decorations will be considered in the size of the page.
Otherwise text is converted to an iterator, where each step is is expected to be a line in the final display, and each line will be run through repr().
- always_page (bool, optional): If False, the
pager will only kick in if text is too big to fit the screen.
- session (Session, optional): If given, this session will be used
to determine the screen width and will receive all output.
- justify (bool, optional): If set, justify long lines in output. Disable for
fixed-format output, like tables.
- justify_kwargs (dict, bool or None, optional): If given, this should
be valid keyword arguments to the utils.justify() function. If False, no justification will be done.
exit_on_lastpage (bool, optional): Immediately exit pager when reaching the last page. use_evtable (bool, optional): If True, each page will be rendered as an
EvTable. For this to work, text must be an iterable, where each element is the table (list of list) to render on that page.
evtable_args (tuple, optional): The args to use for EvTable on each page. evtable_kwargs (dict, optional): The kwargs to use for EvTable on each
page (except table, which is supplied by EvMore per-page).
- kwargs (any, optional): These will be passed on
to the caller.msg method.
evennia.utils.evtable module¶
This is an advanced ASCII table creator. It was inspired by [prettytable](https://code.google.com/p/prettytable/) but shares no code.
Example usage:
- ```python
from evennia.utils import evtable
- table = evtable.EvTable(“Heading1”, “Heading2”,
table=[[1,2,3],[4,5,6],[7,8,9]], border=”cells”)
table.add_column(“This is long data”, “This is even longer data”) table.add_row(“This is a single row”) print table
Result:
`
+----------------------+----------+---+--------------------------+
| Heading1 | Heading2 | | |
+~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~+~~~+~~~~~~~~~~~~~~~~~~~~~~~~~~+
| 1 | 4 | 7 | This is long data |
+----------------------+----------+---+--------------------------+
| 2 | 5 | 8 | This is even longer data |
+----------------------+----------+---+--------------------------+
| 3 | 6 | 9 | |
+----------------------+----------+---+--------------------------+
| This is a single row | | | |
+----------------------+----------+---+--------------------------+
`
As seen, the table will automatically expand with empty cells to make the table symmetric. Tables can be restricted to a given width:
(We could just have added these keywords to the table creation call)
This yields the following result:
`
+-----------+------------+-----------+-----------+
| Heading1 | Heading2 | | |
+~~~~~~~~~~~+~~~~~~~~~~~~+~~~~~~~~~~~+~~~~~~~~~~~+
| 1 | 4 | 7 | This is |
| | | | long data |
+-----------+------------+-----------+-----------+
| | | | This is |
| 2 | 5 | 8 | even |
| | | | longer |
| | | | data |
+-----------+------------+-----------+-----------+
| 3 | 6 | 9 | |
+-----------+------------+-----------+-----------+
| This is a | | | |
| single | | | |
| row | | | |
+-----------+------------+-----------+-----------+
`
Table-columns can be individually formatted. Note that if an individual column is set with a specific width, table auto-balancing will not affect this column (this may lead to the full table being too wide, so be careful mixing fixed-width columns with auto- balancing). Here we change the width and alignment of the column at index 3 (Python starts from 0):
table.reformat_column(3, width=30, align=”r”) print table ```
`
+-----------+-------+-----+-----------------------------+---------+
| Heading1 | Headi | | | |
| | ng2 | | | |
+~~~~~~~~~~~+~~~~~~~+~~~~~+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~+
| 1 | 4 | 7 | This is long data | Test1 |
+-----------+-------+-----+-----------------------------+---------+
| 2 | 5 | 8 | This is even longer data | Test3 |
+-----------+-------+-----+-----------------------------+---------+
| 3 | 6 | 9 | | Test4 |
+-----------+-------+-----+-----------------------------+---------+
| This is a | | | | |
| single | | | | |
| row | | | | |
+-----------+-------+-----+-----------------------------+---------+
`
When adding new rows/columns their data can have its own alignments (left/center/right, top/center/bottom).
If the height is restricted, cells will be restricted from expanding vertically. This will lead to text contents being cropped. Each cell can only shrink to a minimum width and height of 1.
EvTable is intended to be used with [ANSIString](evennia.utils.ansi#ansistring) for supporting ANSI-coloured string types.
When a cell is auto-wrapped across multiple lines, ANSI-reset sequences will be put at the end of each wrapped line. This means that the colour of a wrapped cell will not “bleed”, but it also means that eventual colour outside the table will not transfer “across” a table, you need to re-set the color to have it appear on both sides of the table string.
-
class
evennia.utils.evtable.ANSITextWrapper(width=70, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8, *, max_lines=None, placeholder=' [...]')[source]¶ Bases:
textwrap.TextWrapperThis is a wrapper work class for handling strings with ANSI tags in it. It overloads the standard library TextWrapper class and is used internally in EvTable and has no public methods.
-
_munge_whitespace(text : string) → string[source]¶ Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. ” foo bar
- baz”
becomes ” foo bar baz”.
-
_split(text : string) → [string][source]¶ Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see _wrap_chunks() for full details. As an example, the text
Look, goof-ball – use the -b option!
- breaks into the following chunks:
‘Look,’, ‘ ‘, ‘goof-‘, ‘ball’, ‘ ‘, ‘–’, ‘ ‘, ‘use’, ‘ ‘, ‘the’, ‘ ‘, ‘-b’, ‘ ‘, ‘option!’
- if break_on_hyphens is True, or in:
‘Look,’, ‘ ‘, ‘goof-ball’, ‘ ‘, ‘–’, ‘ ‘, ‘use’, ‘ ‘, ‘the’, ‘ ‘, ‘-b’, ‘ ‘, option!’
otherwise.
-
_wrap_chunks(chunks : [string]) → [string][source]¶ Wrap a sequence of text chunks and return a list of lines of length ‘self.width’ or less. (If ‘break_long_words’ is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo ‘break_long_words’), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a “word”. Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved.
-
-
class
evennia.utils.evtable.EvCell(data, **kwargs)[source]¶ Bases:
objectHolds a single data cell for the table. A cell has a certain width and height and contains one or more lines of data. It can shrink and resize as needed.
-
__init__(data, **kwargs)[source]¶ - Parameters
data (str) – The un-padded data of the entry.
- Kwargs:
- width (int): Desired width of cell. It will pad
to this size.
- height (int): Desired height of cell. it will pad
to this size.
- pad_width (int): General padding width. This can be overruled
by individual settings below.
pad_left (int): Number of extra pad characters on the left. pad_right (int): Number of extra pad characters on the right. pad_top (int): Number of extra pad lines top (will pad with vpad_char). pad_bottom (int): Number of extra pad lines bottom (will pad with vpad_char). pad_char (str)- pad character to use for padding. This is overruled
by individual settings below (default ” “).
- hpad_char (str): Pad character to use both for extra horizontal
padding (default ” “).
- vpad_char (str): Pad character to use for extra vertical padding
and for vertical fill (default ” “).
- fill_char (str): Character used to filling (expanding cells to
desired size). This can be overruled by individual settings below.
hfill_char (str): Character used for horizontal fill (default ” “). vfill_char (str): Character used for vertical fill (default ” “). align (str): Should be one of “l”, “r” or “c” for left-, right- or center
horizontal alignment respectively. Default is left-aligned.
- valign (str): Should be one of “t”, “b” or “c” for top-, bottom and center
vertical alignment respectively. Default is centered.
- border_width (int): General border width. This is overruled
by individual settings below.
border_left (int): Left border width. border_right (int): Right border width. border_top (int): Top border width. border_bottom (int): Bottom border width. border_char (str): This will use a single border char for all borders.
overruled by individual settings below.
border_left_char (str): Char used for left border. border_right_char (str): Char used for right border. border_top_char (str): Char used for top border. border_bottom_char (str): Char user for bottom border. corner_char (str): Character used when two borders cross. (default is “”).
This is overruled by individual settings below.
corner_top_left_char (str): Char used for “nw” corner. corner_top_right_char (str): Char used for “ne” corner. corner_bottom_left_char (str): Char used for “sw” corner. corner_bottom_right_char (str): Char used for “se” corner. crop_string (str): String to use when cropping sideways, default is ‘[…]’. crop (bool): Crop contentof cell rather than expand vertically, default=`False`. enforce_size (bool): If true, the width/height of the cell is
strictly enforced and extra text will be cropped rather than the cell growing vertically.
- Raises
Exception – for impossible cell size requirements where the border width or height cannot fit, or the content is too small.
-
_align(data)[source]¶ Align list of rows of cell. Whitespace characters will be stripped if there is only one whitespace character - otherwise, it’s assumed the caller may be trying some manual formatting in the text.
- Parameters
data (str) – Text to align.
- Returns
Aligned result.
- Return type
text (str)
-
_border(data)[source]¶ Add borders to the cell.
- Parameters
data (str) – Text to surround with borders.
- Returns
Text with borders.
- Return type
text (str)
-
_center(text, width, pad_char)[source]¶ Horizontally center text on line of certain width, using padding.
- Parameters
text (str) – The text to center.
width (int) – How wide the area is (in characters) where text should be centered.
pad_char (str) – Which padding character to use.
- Returns
Centered text.
- Return type
text (str)
-
_crop(text, width)[source]¶ Apply cropping of text.
- Parameters
text (str) – The text to crop.
width (int) – The width to crop text to.
-
_fit_width(data)[source]¶ Split too-long lines to fit the desired width of the Cell.
- Parameters
data (str) – Text to adjust to the cell’s width.
- Returns
The adjusted text.
- Return type
adjusted data (str)
Notes
This also updates raw_width.
-
_pad(data)[source]¶ Pad data with extra characters on all sides.
- Parameters
data (str) – Text to pad.
- Returns
Padded text.
- Return type
text (str)
-
_split_lines(text)[source]¶ Simply split by linebreaks
- Parameters
text (str) – text to split.
- Returns
split text.
- Return type
split (list)
-
_valign(data)[source]¶ Align cell vertically
- Parameters
data (str) – Text to align.
- Returns
Vertically aligned text.
- Return type
text (str)
-
get_height()[source]¶ Get natural height of cell, including padding.
- Returns
Height of cell.
- Return type
natural_height (int)
-
get_min_height()[source]¶ Get the minimum possible height of cell, including at least one line for data.
- Returns
The mininum height of cell.
- Return type
min_height (int)
-
get_min_width()[source]¶ Get the minimum possible width of cell, including at least one character-width for data.
- Returns
The minimum width of cell.
- Return type
min_width (int)
-
get_width()[source]¶ Get natural width of cell, including padding.
- Returns
Width of cell.
- Return type
natural_width (int)
-
-
class
evennia.utils.evtable.EvColumn(*args, **kwargs)[source]¶ Bases:
objectThis class holds a list of Cells to represent a column of a table. It holds operations and settings that affect all cells in the column.
Columns are not intended to be used stand-alone; they should be incorporated into an EvTable (like EvCells)
-
__init__(*args, **kwargs)[source]¶ - Parameters
for each row in the column (Text) –
- Kwargs:
All EvCell.__init_ keywords are available, these settings will be persistently applied to every Cell in the column.
-
_balance(**kwargs)[source]¶ Make sure to adjust the width of all cells so we form a coherent and lined-up column. Will enforce column-specific options to cells.
- Kwargs:
Extra keywords to modify the column setting. Same keywords as in EvCell.__init__.
-
add_rows(*args, **kwargs)[source]¶ Add new cells to column. They will be inserted as a series of rows. It will inherit the options of the rest of the column’s cells (use update to change options).
- Parameters
for the new cells (Texts) –
ypos (int, optional) – Index position in table before which to insert the new column. Uses Python indexing, so to insert at the top, use ypos=0. If not given, data will be inserted at the end of the column.
- Kwargs:
Available keywods as per EvCell.__init__.
-
-
class
evennia.utils.evtable.EvTable(*args, **kwargs)[source]¶ Bases:
objectThe table class holds a list of EvColumns, each consisting of EvCells so that the result is a 2D matrix.
-
__init__(*args, **kwargs)[source]¶ - Parameters
texts for the table. (Header) –
- Kwargs:
- table (list of lists or list of EvColumns, optional):
This is used to build the table in a quick way. If not given, the table will start out empty and add_ methods need to be used to add rows/columns.
- header (bool, optional): True/False - turn off the
header texts (*args) being treated as a header (such as not adding extra underlining)
- pad_width (int, optional): How much empty space to pad your cells with
(default is 1)
- border (str, optional)): The border style to use. This is one of
None - No border drawing at all.
“table” - only a border around the whole table.
“tablecols” - table and column borders. (default)
“header” - only border under header.
“cols” - only vertical borders.
“incols” - vertical borders, no outer edges.
“rows” - only borders between rows.
“cells” - border around all cells.
- border_width (int, optional): Width of table borders, if border is active.
Note that widths wider than 1 may give artifacts in the corners. Default is 1.
- corner_char (str, optional): Character to use in corners when border is active.
Default is +.
- corner_top_left_char (str, optional): Character used for “nw” corner of table.
Defaults to corner_char.
- corner_top_right_char (str, optional): Character used for “ne” corner of table.
Defaults to corner_char.
- corner_bottom_left_char (str, optional): Character used for “sw” corner of table.
Defaults to corner_char.
- corner_bottom_right_char (str, optional): Character used for “se” corner of table.
Defaults to corner_char.
- pretty_corners (bool, optional): Use custom characters to
make the table corners look “rounded”. Uses UTF-8 characters. Defaults to False for maximum compatibility with various displays that may occationally have issues with UTF-8 characters.
- header_line_char (str, optional): Character to use for underlining
the header row (default is ‘~’). Requires border to not be None.
- width (int, optional): Fixed width of table. If not set,
width is set by the total width of each column. This will resize individual columns in the vertical direction to fit.
- height (int, optional): Fixed height of table. Defaults to being unset. Width is
still given precedence. If given, table cells will crop text rather than expand vertically.
- evenwidth (bool, optional): Used with the width keyword. Adjusts columns to have as even width as
possible. This often looks best also for mixed-length tables. Default is False.
- maxwidth (int, optional): This will set a maximum width
of the table while allowing it to be smaller. Only if it grows wider than this size will it be resized by expanding horizontally (or crop height is given). This keyword has no meaning if width is set.
- Raises
Exception – If given erroneous input or width settings for the data.
Notes
Beyond those table-specific keywords, the non-overlapping keywords of EcCell.__init__ are also available. These will be passed down to every cell in the table.
-
_balance()[source]¶ Balance the table. This means to make sure all cells on the same row have the same height, that all columns have the same number of rows and that the table fits within the given width.
-
_cellborders(ix, iy, nx, ny, **kwargs)[source]¶ Adds borders to the table by adjusting the input kwarg to instruct cells to build a border in the right positions.
- Parameters
ix (int) – x index positions in table.
iy (int) – y index positions in table.
nx (int) – x size of table.
ny (int) – y size of table.
- Kwargs:
Keywords as per EvTable.__init__.
- Returns
string with the correct borders.
- Return type
table (str)
Notes
A copy of the kwarg is returned to the cell. This is method is called by self._borders.
-
_generate_lines()[source]¶ Generates lines across all columns (each cell may contain multiple lines) This will also balance the table.
-
add_column(*args, **kwargs)[source]¶ Add a column to table. If there are more rows in new column than there are rows in the current table, the table will expand with empty rows in the other columns. If too few, the new column with get new empty rows. All filling rows are added to the end.
- Parameters
args (EvColum or multiple strings) – Either a single EvColumn instance or a number of data string arguments to be used to create a new column.
header (str, optional) – The header text for the column
xpos (int, optional) – Index position in table before which to input new column. If not given, column will be added to the end of the table. Uses Python indexing (so first column is xpos=0)
- Kwargs:
Other keywords as per Cell.__init__.
-
add_header(*args, **kwargs)[source]¶ Add header to table. This is a number of texts to be put at the top of the table. They will replace an existing header.
- Parameters
args (str) – These strings will be used as the header texts.
- Kwargs:
Same keywords as per EvTable.__init__. Will be applied to the new header’s cells.
-
add_row(*args, **kwargs)[source]¶ Add a row to table (not a header). If there are more cells in the given row than there are cells in the current table the table will be expanded with empty columns to match. These will be added to the end of the table. In the same way, adding a line with too few cells will lead to the last ones getting padded.
- Parameters
args (str) – Any number of string argumnets to use as the data in the row (one cell per argument).
ypos (int, optional) – Index position in table before which to input new row. If not given, will be added to the end of the table. Uses Python indexing (so first row is ypos=0)
- Kwargs:
Other keywords are as per EvCell.__init__.
-
get()[source]¶ Return lines of table as a list.
- Returns
The lines of the table, in order.
- Return type
table_lines (list)
-
-
evennia.utils.evtable._to_ansi(obj)[source]¶ convert to ANSIString.
- Parameters
obj (str) – Convert incoming text to be ANSI aware ANSIStrings.
-
evennia.utils.evtable.fill(text, width=78, **kwargs)[source]¶ Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in ‘text’ to fit in lines of no more than ‘width’ columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space.
- Parameters
text (str) – Text to fill.
width (int, optional) – Width of fill area.
- Kwargs:
See TextWrapper class for available keyword args to customize filling behaviour.
-
evennia.utils.evtable.wrap(text, width=78, **kwargs)[source]¶ Wrap a single paragraph of text, returning a list of wrapped lines.
Reformat the single paragraph in ‘text’ so it fits in lines of no more than ‘width’ columns, and return a list of wrapped lines. By default, tabs in ‘text’ are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to
- Parameters
text (str) – Text to wrap.
width (int, optional) – Width to wrap text to.
- Kwargs:
See TextWrapper class for available keyword args to customize wrapping behaviour.
evennia.utils.gametime module¶
The gametime module handles the global passage of time in the mud.
It also supplies some useful methods to convert between in-mud time and real-world time as well allows to get the total runtime of the server and the current uptime.
-
class
evennia.utils.gametime.TimeScript(*args, **kwargs)[source]¶ Bases:
evennia.scripts.scripts.DefaultScriptGametime-sensitive script.
-
exception
DoesNotExist¶ Bases:
evennia.scripts.scripts.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.scripts.scripts.MultipleObjectsReturned
-
_meta= <Options for TimeScript>¶
-
path= 'evennia.utils.gametime.TimeScript'¶
-
typename= 'TimeScript'¶
-
exception
-
evennia.utils.gametime.gametime(absolute=False)[source]¶ Get the total gametime of the server since first start (minus downtimes)
- Parameters
absolute (bool, optional) – Get the absolute game time, including the epoch. This could be converted to an absolute in-game date.
- Returns
The gametime as a virtual timestamp.
- Return type
time (float)
Notes
If one is using a standard calendar, one could convert the unformatted return to a date using Python’s standard datetime module like this: datetime.datetime.fromtimestamp(gametime(absolute=True))
-
evennia.utils.gametime.portal_uptime()[source]¶ Get the current uptime of the portal.
- Returns
The uptime of the portal.
- Return type
time (float)
-
evennia.utils.gametime.real_seconds_until(sec=None, min=None, hour=None, day=None, month=None, year=None)[source]¶ Return the real seconds until game time.
- Parameters
sec (int or None) – number of absolute seconds.
min (int or None) – number of absolute minutes.
hour (int or None) – number of absolute hours.
day (int or None) – number of absolute days.
month (int or None) – number of absolute months.
year (int or None) – number of absolute years.
- Returns
The number of real seconds before the given game time is up.
Example
real_seconds_until(hour=5, min=10, sec=0)
If the game time is 5:00, TIME_FACTOR is set to 2 and you ask the number of seconds until it’s 5:10, then this function should return 300 (5 minutes).
-
evennia.utils.gametime.reset_gametime()[source]¶ Resets the game time to make it start from the current time. Note that the epoch set by settings.TIME_GAME_EPOCH will still apply.
-
evennia.utils.gametime.runtime()[source]¶ Get the total runtime of the server since first start (minus downtimes)
- Parameters
format (bool, optional) – Format into a time representation.
- Returns
- The runtime or the same time split up
into time units.
- Return type
time (float or tuple)
-
evennia.utils.gametime.schedule(callback, repeat=False, sec=None, min=None, hour=None, day=None, month=None, year=None)[source]¶ Call a callback at a given in-game time.
- Parameters
callback (function) – The callback function that will be called. Note that the callback must be a module-level function, since the script will be persistent.
repeat (bool, optional) – Defines if the callback should be called regularly at the specified time.
sec (int or None) – Number of absolute game seconds at which to run repeat.
min (int or None) – Number of absolute minutes.
hour (int or None) – Number of absolute hours.
day (int or None) – Number of absolute days.
month (int or None) – Number of absolute months.
year (int or None) – Number of absolute years.
- Returns
The created Script handling the sceduling.
- Return type
script (Script)
Examples
schedule(func, min=5, sec=0) # Will call 5 minutes past the next (in-game) hour. schedule(func, hour=2, min=30, sec=0) # Will call the next (in-game) day at 02:30.
evennia.utils.inlinefuncs module¶
Inline functions (nested form).
This parser accepts nested inlinefunctions on the form
`
$funcname(arg, arg, ...)
`
embedded in any text where any arg can be another $funcname{} call. This functionality is turned off by default - to activate, settings.INLINEFUNC_ENABLED must be set to True.
Each token starts with “$funcname(” where there must be no space between the $funcname and (. It ends with a matched ending parentesis. “)”.
Inside the inlinefunc definition, one can use ` to escape. This is mainly needed for escaping commas in flowing text (which would otherwise be interpreted as an argument separator), or to escape `} when not intended to close the function block. Enclosing text in matched “”” (triple quotes) or ‘’’ (triple single-quotes) will also escape everything within without needing to escape individual characters.
The available inlinefuncs are defined as global-level functions in modules defined by settings.INLINEFUNC_MODULES. They are identified by their function name (and ignored if this name starts with _). They should be on the following form:
```python def funcname (*args, **kwargs):
# …
Here, the arguments given to $funcname(arg1,arg2) will appear as the *args tuple. This will be populated by the arguments given to the inlinefunc in-game - the only part that will be available from in-game. **kwargs are not supported from in-game but are only used internally by Evennia to make details about the caller available to the function. The kwarg passed to all functions is session, the Sessionobject for the object seeing the string. This may be None if the string is sent to a non-puppetable object. The inlinefunc should never raise an exception.
There are two reserved function names: - “nomatch”: This is called if the user uses a functionname that is
not registered. The nomatch function will get the name of the not-found function as its first argument followed by the normal arguments to the given function. If not defined the default effect is to print <UNKNOWN> to replace the unknown function.
“stackfull”: This is called when the maximum nested function stack is reached. When this happens, the original parsed string is returned and the result of the stackfull inlinefunc is appended to the end. By default this is an error message.
- Error handling:
Syntax errors, notably not completely closing all inlinefunc blocks, will lead to the entire string remaining unparsed.
-
class
evennia.utils.inlinefuncs.ParseStack(*args, **kwargs)[source]¶ Bases:
listCustom stack that always concatenates strings together when the strings are added next to one another. Tuples are stored separately and None is used to mark that a string should be broken up into a new chunk. Below is the resulting stack after separately appending 3 strings, None, 2 strings, a tuple and finally 2 strings:
[string + string + string, None string + string, tuple, string + string]
-
evennia.utils.inlinefuncs.clr(*args, **kwargs)[source]¶ Inlinefunc. Colorizes nested text.
- Parameters
startclr (str, optional) – An ANSI color abbreviation without the prefix |, such as r (red foreground) or [r (red background).
text (str, optional) – Text
endclr (str, optional) – The color to use at the end of the string. Defaults to |n (reset-color).
- Kwargs:
session (Session): Session object triggering inlinefunc.
Example
$clr(startclr, text, endclr)
-
evennia.utils.inlinefuncs.crop(*args, **kwargs)[source]¶ Inlinefunc. Crops ingoing text to given widths.
- Parameters
text (str, optional) – Text to crop.
width (str, optional) – Will be converted to an integer. Width of crop in characters.
suffix (str, optional) – End string to mark the fact that a part of the string was cropped. Defaults to […].
- Kwargs:
session (Session): Session performing the crop.
Example
$crop(text, width=78, suffix=’[…]’)
-
evennia.utils.inlinefuncs.initialize_nick_templates(in_template, out_template)[source]¶ Initialize the nick templates for matching and remapping a string.
- Parameters
in_template (str) – The template to be used for nick recognition.
out_template (str) – The template to be used to replace the string matched by the in_template.
- Returns
Regex to match against strings template (str): Template with markers {arg1}, {arg2}, etc for
replacement using the standard .format method.
- Return type
regex (regex)
- Raises
NickTemplateInvalid – If the in/out template does not have a matching number of $args.
-
evennia.utils.inlinefuncs.nomatch(name, *args, **kwargs)[source]¶ Default implementation of nomatch returns the function as-is as a string.
-
evennia.utils.inlinefuncs.pad(*args, **kwargs)[source]¶ Inlinefunc. Pads text to given width.
- Parameters
text (str, optional) – Text to pad.
width (str, optional) – Will be converted to integer. Width of padding.
align (str, optional) – Alignment of padding; one of ‘c’, ‘l’ or ‘r’.
fillchar (str, optional) – Character used for padding. Defaults to a space.
- Kwargs:
session (Session): Session performing the pad.
Example
$pad(text, width, align, fillchar)
-
evennia.utils.inlinefuncs.parse_inlinefunc(string, strip=False, available_funcs=None, stacktrace=False, **kwargs)[source]¶ Parse the incoming string.
- Parameters
string (str) – The incoming string to parse.
strip (bool, optional) – Whether to strip function calls rather than execute them.
available_funcs (dict, optional) – Define an alternative source of functions to parse for. If unset, use the functions found through settings.INLINEFUNC_MODULES.
stacktrace (bool, optional) – If set, print the stacktrace to log.
- Kwargs:
- session (Session): This is sent to this function by Evennia when triggering
it. It is passed to the inlinefunc.
kwargs (any): All other kwargs are also passed on to the inlinefunc.
-
evennia.utils.inlinefuncs.parse_nick_template(string, template_regex, outtemplate)[source]¶ Parse a text using a template and map it to another template
- Parameters
string (str) – The input string to processj
template_regex (regex) – A template regex created with initialize_nick_template.
outtemplate (str) – The template to which to map the matches produced by the template_regex. This should have $1, $2, etc to match the regex.
evennia.utils.logger module¶
Logging facilities
These are thin wrappers on top of Twisted’s logging facilities; logs are all directed either to stdout (if Evennia is running in interactive mode) or to $GAME_DIR/server/logs.
The log_file() function uses its own threading system to log to arbitrary files in $GAME_DIR/server/logs.
Note: All logging functions have two aliases, log_type() and log_typemsg(). This is for historical, back-compatible reasons.
-
class
evennia.utils.logger.EvenniaLogFile(name, directory, rotateLength=1000000, defaultMode=None, maxRotatedFiles=None)[source]¶ Bases:
twisted.python.logfile.LogFileA rotating logfile based off Twisted’s LogFile. It overrides the LogFile’s rotate method in order to append some of the last lines of the previous log to the start of the new log, in order to preserve a continuous chat history for channel log files.
-
num_lines_to_append= 20¶
-
readlines(*args, **kwargs)[source]¶ Convenience method for accessing our _file attribute’s readlines method, which is used in tail_log_function. :param *args: same args as file.readlines :param **kwargs: same kwargs as file.readlines
- Returns
lines from our _file attribute.
- Return type
lines (list)
-
rotate()[source]¶ Rotates our log file and appends some number of lines from the previous log to the start of the new one.
-
seek(*args, **kwargs)[source]¶ Convenience method for accessing our _file attribute’s seek method, which is used in tail_log_function. :param *args: Same args as file.seek :param **kwargs: Same kwargs as file.seek
-
settings= <LazySettings "server.conf.settings">¶
-
-
class
evennia.utils.logger.PortalLogObserver(f)[source]¶ Bases:
twisted.python.log.FileLogObserverReformat logging
-
prefix= ' |Portal| '¶
-
timeFormat= None¶
-
-
class
evennia.utils.logger.ServerLogObserver(f)[source]¶ Bases:
evennia.utils.logger.PortalLogObserver-
prefix= ' '¶
-
-
class
evennia.utils.logger.WeeklyLogFile(name, directory, defaultMode=None, day_rotation=7, max_size=1000000)[source]¶ Bases:
twisted.python.logfile.DailyLogFileLog file that rotates once per week by default. Overrides key methods to change format.
-
__init__(name, directory, defaultMode=None, day_rotation=7, max_size=1000000)[source]¶ - Parameters
name (str) – Name of log file.
directory (str) – Directory holding the file.
defaultMode (str) – Permissions used to create file. Defaults to current permissions of this file if it exists.
day_rotation (int) – How often to rotate the file.
max_size (int) – Max size of log file before rotation (regardless of time). Defaults to 1M.
-
suffix(tupledate)[source]¶ Return the suffix given a (year, month, day) tuple or unixtime. Format changed to have 03 for march instead of 3 etc (retaining unix file order)
If we get duplicate suffixes in location (due to hitting size limit), we append __1, __2 etc.
Examples
server.log.2020_01_29 server.log.2020_01_29__1 server.log.2020_01_29__2
-
-
evennia.utils.logger._open_log_file(filename)[source]¶ Helper to open the log file (always in the log dir) and cache its handle. Will create a new file in the log dir if one didn’t exist.
To avoid keeping the filehandle open indefinitely we reset it every _LOG_FILE_HANDLE_RESET accesses. This may help resolve issues for very long uptimes and heavy log use.
-
evennia.utils.logger.log_dep(depmsg)[source]¶ Prints a deprecation message.
- Parameters
depmsg (str) – The deprecation message to log.
-
evennia.utils.logger.log_depmsg(depmsg)¶ Prints a deprecation message.
- Parameters
depmsg (str) – The deprecation message to log.
-
evennia.utils.logger.log_err(errmsg)[source]¶ Prints/logs an error message to the server log.
- Parameters
errmsg (str) – The message to be logged.
-
evennia.utils.logger.log_errmsg(errmsg)¶ Prints/logs an error message to the server log.
- Parameters
errmsg (str) – The message to be logged.
-
evennia.utils.logger.log_file(msg, filename='game.log')[source]¶ Arbitrary file logger using threads.
- Parameters
msg (str) – String to append to logfile.
filename (str, optional) – Defaults to ‘game.log’. All logs will appear in the logs directory and log entries will start on new lines following datetime info.
-
evennia.utils.logger.log_info(infomsg)[source]¶ Prints any generic debugging/informative info that should appear in the log.
infomsg: (string) The message to be logged.
-
evennia.utils.logger.log_infomsg(infomsg)¶ Prints any generic debugging/informative info that should appear in the log.
infomsg: (string) The message to be logged.
-
evennia.utils.logger.log_msg(msg)[source]¶ Wrapper around log.msg call to catch any exceptions that might occur in logging. If an exception is raised, we’ll print to stdout instead.
- Parameters
msg – The message that was passed to log.msg
-
evennia.utils.logger.log_sec(secmsg)[source]¶ Prints a security-related message.
- Parameters
secmsg (str) – The security message to log.
-
evennia.utils.logger.log_secmsg(secmsg)¶ Prints a security-related message.
- Parameters
secmsg (str) – The security message to log.
-
evennia.utils.logger.log_server(servermsg)[source]¶ This is for the Portal to log captured Server stdout messages (it’s usually only used during startup, before Server log is open)
-
evennia.utils.logger.log_trace(errmsg=None)[source]¶ Log a traceback to the log. This should be called from within an exception.
- Parameters
errmsg (str, optional) – Adds an extra line with added info at the end of the traceback in the log.
-
evennia.utils.logger.log_tracemsg(errmsg=None)¶ Log a traceback to the log. This should be called from within an exception.
- Parameters
errmsg (str, optional) – Adds an extra line with added info at the end of the traceback in the log.
-
evennia.utils.logger.log_warn(warnmsg)[source]¶ Prints/logs any warnings that aren’t critical but should be noted.
- Parameters
warnmsg (str) – The message to be logged.
-
evennia.utils.logger.log_warnmsg(warnmsg)¶ Prints/logs any warnings that aren’t critical but should be noted.
- Parameters
warnmsg (str) – The message to be logged.
-
evennia.utils.logger.tail_log_file(filename, offset, nlines, callback=None)[source]¶ Return the tail of the log file.
- Parameters
filename (str) – The name of the log file, presumed to be in the Evennia log dir.
offset (int) – The line offset from the end of the file to start reading from. 0 means to start at the latest entry.
nlines (int) – How many lines to return, counting backwards from the offset. If file is shorter, will get all lines.
callback (callable, optional) – A function to manage the result of the asynchronous file access. This will get a list of lines. If unset, the tail will happen synchronously.
- Returns
- This will be a deferred if callable is given,
otherwise it will be a list with The nline entries from the end of the file, or all if the file is shorter than nlines.
- Return type
lines (deferred or list)
-
evennia.utils.logger.timeformat(when=None)[source]¶ This helper function will format the current time in the same way as the twisted logger does, including time zone info. Only difference from official logger is that we only use two digits for the year and don’t show timezone for CET times.
- Parameters
when (int, optional) – This is a time in POSIX seconds on the form given by time.time(). If not given, this function will use the current time.
- Returns
A formatted string of the given time.
- Return type
timestring (str)
evennia.utils.optionclasses module¶
-
class
evennia.utils.optionclasses.BaseOption(handler, key, description, default)[source]¶ Bases:
objectAbstract Class to deal with encapsulating individual Options. An Option has a name/key, a description to display in relevant commands and menus, and a default value. It saves to the owner’s Attributes using its Handler’s save category.
Designed to be extremely overloadable as some options can be cantankerous.
- Properties:
valid: Shortcut to the loaded VALID_HANDLER. validator_key (str): The key of the Validator this uses.
-
__init__(handler, key, description, default)[source]¶ - Parameters
handler (OptionHandler) – The OptionHandler that ‘owns’ this Option.
key (str) – The name this will be used for storage in a dictionary. Must be unique per OptionHandler.
description (str) – What this Option’s text will show in commands and menus.
default – A default value for this Option.
-
property
changed¶
-
property
default¶
-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
display(**kwargs)[source]¶ Renders the Option’s value as something pretty to look at.
- Kwargs:
- any (any): These are options passed by the caller to potentially
customize display dynamically.
- Returns
- How the stored value should be projected to users (e.g. a raw
timedelta is pretty ugly).
- Return type
str
-
load()[source]¶ Takes the provided save data, validates it, and gets this Option ready to use.
- Returns
Whether loading was successful.
- Return type
-
save(**kwargs)[source]¶ Stores the current value using .handler.save_handler(self.key, value, **kwargs) where kwargs are a combination of those passed into this function and the ones specified by the OptionHandler.
- Kwargs:
- any (any): Not used by default. These are passed in from self.set
and allows the option to let the caller customize saving by overriding or extend the default save kwargs
-
serialize()[source]¶ Serializes the save data for Attribute storage.
- Returns
Whatever is best for storage.
- Return type
any (any)
-
set(value, **kwargs)[source]¶ Takes user input and stores appropriately. This method allows for passing extra instructions into the validator.
- Parameters
value (str) – The new value of this Option.
kwargs (any) – Any kwargs will be passed into self.validate(value, **kwargs) and self.save(**kwargs).
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
property
value¶
-
class
evennia.utils.optionclasses.Boolean(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
display(**kwargs)[source]¶ Renders the Option’s value as something pretty to look at.
- Kwargs:
- any (any): These are options passed by the caller to potentially
customize display dynamically.
- Returns
- How the stored value should be projected to users (e.g. a raw
timedelta is pretty ugly).
- Return type
str
-
serialize()[source]¶ Serializes the save data for Attribute storage.
- Returns
Whatever is best for storage.
- Return type
any (any)
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.Color(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
display(**kwargs)[source]¶ Renders the Option’s value as something pretty to look at.
- Kwargs:
- any (any): These are options passed by the caller to potentially
customize display dynamically.
- Returns
- How the stored value should be projected to users (e.g. a raw
timedelta is pretty ugly).
- Return type
str
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.Datetime(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
serialize()[source]¶ Serializes the save data for Attribute storage.
- Returns
Whatever is best for storage.
- Return type
any (any)
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.Duration(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
serialize()[source]¶ Serializes the save data for Attribute storage.
- Returns
Whatever is best for storage.
- Return type
any (any)
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.Email(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.Future(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.Datetime-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.Lock(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.Text-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.PositiveInteger(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.SignedInteger(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
-
class
evennia.utils.optionclasses.Text(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
-
class
evennia.utils.optionclasses.Timezone(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
property
default¶
-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
serialize()[source]¶ Serializes the save data for Attribute storage.
- Returns
Whatever is best for storage.
- Return type
any (any)
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
property
-
class
evennia.utils.optionclasses.UnsignedInteger(handler, key, description, default)[source]¶ Bases:
evennia.utils.optionclasses.BaseOption-
deserialize(save_data)[source]¶ Perform sanity-checking on the save data as it is loaded from storage. This isn’t the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object.
- Parameters
save_data – The data to check.
- Returns
- Whatever the Option needs to track, like a string or a
datetime. The display hook is responsible for what is actually displayed to user.
- Return type
any (any)
-
validate(value, **kwargs)[source]¶ Validate user input, which is presumed to be a string.
- Parameters
value (str) – User input.
account (AccountDB) – The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account’s timezone affecting how their datetime entries are processed.
- Returns
The results of the validation.
- Return type
any (any)
- Raises
ValidationError – If input value failed validation.
-
validator_key= 'unsigned_integer'¶
-
evennia.utils.optionhandler module¶
-
class
evennia.utils.optionhandler.InMemorySaveHandler[source]¶ Bases:
objectFallback SaveHandler, implementing a minimum of the required save mechanism and storing data in memory.
-
class
evennia.utils.optionhandler.OptionHandler(obj, options_dict=None, savefunc=None, loadfunc=None, save_kwargs=None, load_kwargs=None)[source]¶ Bases:
objectThis is a generic Option handler. Retrieve options either as properties on this handler or by using the .get method.
This is used for Account.options but it could be used by Scripts or Objects just as easily. All it needs to be provided is an options_dict.
-
__init__(obj, options_dict=None, savefunc=None, loadfunc=None, save_kwargs=None, load_kwargs=None)[source]¶ Initialize an OptionHandler.
- Parameters
obj (object) – The object this handler sits on. This is usually a TypedObject.
options_dict (dict) – A dictionary of option keys, where the values are options. The format of those tuples is: (‘key’, “Description to show”, ‘option_type’, <default value>)
savefunc (callable) – A callable for all options to call when saving itself. It will be called as savefunc(key, value, **save_kwargs). A common one to pass would be AttributeHandler.add.
loadfunc (callable) – A callable for all options to call when loading data into itself. It will be called as loadfunc(key, default=default, **load_kwargs). A common one to pass would be AttributeHandler.get.
save_kwargs (any) – Optional extra kwargs to pass into savefunc above.
load_kwargs (any) – Optional extra kwargs to pass into loadfunc above.
Notes
Both loadfunc and savefunc must be specified. If only one is given, the other will be ignored and in-memory storage will be used.
-
_load_option(key)[source]¶ Loads option on-demand if it has not been loaded yet.
- Parameters
key (str) – The option being loaded.
Returns:
-
all(return_objs=False)[source]¶ Get all options defined on this handler.
- Parameters
return_objs (bool, optional) – Return the actual Option objects rather than their values.
- Returns
- All options on this handler, either {key: value}
or {key: <Option>} if return_objs is True.
- Return type
all_options (dict)
-
get(key, default=None, return_obj=False, raise_error=False)[source]¶ Retrieves an Option stored in the handler. Will load it if it doesn’t exist.
- Parameters
key (str) – The option key to retrieve.
default (any) – What to return if the option is defined.
return_obj (bool, optional) – If True, returns the actual option object instead of its value.
raise_error (bool, optional) – Raise Exception if key is not found in options.
- Returns
An option value the Option itself.
- Return type
option_value (any or Option)
- Raises
KeyError – If option is not defined.
-
set(key, value, **kwargs)[source]¶ Change an individual option.
- Parameters
key (str) – The key of an option that can be changed. Allows partial matching.
value (str) – The value that should be checked, coerced, and stored.:
kwargs (any, optional) – These are passed into the Option’s validation function, save function and display function and allows to customize either.
- Returns
Value stored in option, after validation.
- Return type
value (any)
-
-
evennia.utils.optionhandler._GA()¶ Return getattr(self, name).
-
evennia.utils.optionhandler._SA()¶ Implement setattr(self, name, value).
evennia.utils.picklefield module¶
Pickle field implementation for Django.
Modified for Evennia by Griatch and the Evennia community.
-
class
evennia.utils.picklefield.PickledFormField(*args, **kwargs)[source]¶ Bases:
django.forms.fields.CharFieldThis represents one input field for the form.
-
clean(value)[source]¶ Validate the given value and return its “cleaned” value as an appropriate Python object. Raise ValidationError for any errors.
-
default_error_messages= {'invalid': 'This is not a Python Literal. You can store things like strings, integers, or floats, but you must do it by typing them as you would type them in the Python Interpreter. For instance, strings must be surrounded by quote marks. We have converted it to a string for your convenience. If it is acceptable, please hit save again.', 'required': 'This field is required.'}¶
-
widget¶ alias of
PickledWidget
-
-
class
evennia.utils.picklefield.PickledObject[source]¶ Bases:
strA subclass of string so it can be told whether a string is a pickled object or not (if the object is an instance of this class then it must [well, should] be a pickled one).
Only really useful for passing pre-encoded values to
defaultwithdbsafe_encode, not that doing so is necessary. If you remove PickledObject and its references, you won’t be able to pass in pre-encoded values anymore, but you can always just pass in the python objects themselves.
-
class
evennia.utils.picklefield.PickledObjectField(*args, **kwargs)[source]¶ Bases:
django.db.models.fields.FieldA field that will accept any python object and store it in the database. PickledObjectField will optionally compress its values if declared with the keyword argument
compress=True.Does not actually encode and compress
Noneobjects (although you can still do lookups using None). This way, it is still possible to use theisnulllookup type correctly.-
from_db_value(value, *args)[source]¶ B64decode and unpickle the object, optionally decompressing it.
If an error is raised in de-pickling and we’re sure the value is a definite pickle, the error is allowed to propagate. If we aren’t sure if the value is a pickle or not, then we catch the error and return the original value instead.
-
get_db_prep_value(value, connection=None, prepared=False)[source]¶ Pickle and b64encode the object, optionally compressing it.
The pickling protocol is specified explicitly (by default 2), rather than as -1 or HIGHEST_PROTOCOL, because we don’t want the protocol to change over time. If it did,
exactandinlookups would likely fail, since pickle would now be generating a different string.
-
get_default()[source]¶ Returns the default value for this field.
The default implementation on models.Field calls force_str on the default, which means you can’t set arbitrary Python objects as the default. To fix this, we just return the value without calling force_str on it. Note that if you set a callable as a default, the field will still call it. It will not try to pickle and encode it.
-
-
class
evennia.utils.picklefield.PickledWidget(attrs=None)[source]¶ Bases:
django.forms.widgets.TextareaThis is responsible for outputting HTML representing a given field.
-
property
media¶
-
property
-
class
evennia.utils.picklefield._ObjectWrapper(obj)[source]¶ Bases:
objectA class used to wrap object that have properties that may clash with the ORM internals.
For example, objects with the prepare_database_save property such as django.db.Model subclasses won’t work under certain conditions and the same apply for trying to retrieve any callable object.
-
_obj¶
-
evennia.utils.search module¶
This is a convenient container gathering all the main search methods for the various database tables.
It is intended to be used e.g. as
> from evennia.utils import search > match = search.objects(…)
Note that this is not intended to be a complete listing of all search methods! You need to refer to the respective manager to get all possible search methods. To get to the managers from your code, import the database model and call its ‘objects’ property.
Also remember that all commands in this file return lists (also if there is only one match) unless noted otherwise.
- Example: To reach the search method ‘get_object_with_account’
in evennia/objects/managers.py:
> from evennia.objects.models import ObjectDB > match = Object.objects.get_object_with_account(…)
-
evennia.utils.search.search_object(searchdata, attribute_name=None, typeclass=None, candidates=None, exact=True, use_dbref=True)¶ Search as an object globally or in a list of candidates and return results. The result is always an Object. Always returns a list.
- Parameters
searchdata (str or Object) – The entity to match for. This is usually a key string but may also be an object itself. By default (if no attribute_name is set), this will search object.key and object.aliases in order. Can also be on the form #dbref, which will (if exact=True) be matched against primary key.
attribute_name (str) – Use this named Attribute to match searchdata against, instead of the defaults. If this is the name of a database field (with or without the db_ prefix), that will be matched too.
typeclass (str or TypeClass) – restrict matches to objects having this typeclass. This will help speed up global searches.
candidates (list) – If supplied, search will only be performed among the candidates in this list. A common list of candidates is the contents of the current location searched.
exact (bool) – Match names/aliases exactly or partially. Partial matching matches the beginning of words in the names/aliases, using a matching routine to separate multiple matches in names with multiple components (so “bi sw” will match “Big sword”). Since this is more expensive than exact matching, it is recommended to be used together with the candidates keyword to limit the number of possibilities. This value has no meaning if searching for attributes/properties.
use_dbref (bool) – If False, bypass direct lookup of a string on the form #dbref and treat it like any string.
- Returns
Matching objects
- Return type
matches (list)
-
evennia.utils.search.search_account(ostring, exact=True, typeclass=None)¶ Searches for a particular account by name or database id.
- Parameters
ostring (str or int) – A key string or database id.
exact (bool, optional) – Only valid for string matches. If True, requires exact (non-case-sensitive) match, otherwise also match also keys containing the ostring (non-case-sensitive fuzzy match).
typeclass (str or Typeclass, optional) – Limit the search only to accounts of this typeclass.
-
evennia.utils.search.search_script(ostring, obj=None, only_timed=False, typeclass=None)¶ Search for a particular script.
- Parameters
ostring (str) – Search criterion - a script dbef or key.
obj (Object, optional) – Limit search to scripts defined on this object
only_timed (bool) – Limit search only to scripts that run on a timer.
typeclass (class or str) – Typeclass or path to typeclass.
-
evennia.utils.search.search_message(sender=None, receiver=None, freetext=None, dbref=None)¶ Search the message database for particular messages. At least one of the arguments must be given to do a search.
- Parameters
sender (Object or Account, optional) – Get messages sent by a particular account or object
receiver (Object, Account or Channel, optional) – Get messages received by a certain account,object or channel
freetext (str) – Search for a text string in a message. NOTE: This can potentially be slow, so make sure to supply one of the other arguments to limit the search.
dbref (int) – The exact database id of the message. This will override all other search criteria since it’s unique and always gives only one match.
- Returns
A list of message matches or a single match if dbref was given.
- Return type
messages (list or Msg)
-
evennia.utils.search.search_channel(ostring, exact=True)¶ Search the channel database for a particular channel.
- Parameters
ostring (str) – The key or database id of the channel.
exact (bool, optional) – Require an exact (but not case sensitive) match.
-
evennia.utils.search.search_help_entry(ostring, help_category=None)¶ Retrieve a search entry object.
- Parameters
ostring (str) – The help topic to look for.
category (str) – Limit the search to a particular help topic
-
evennia.utils.search.search_script_tag(key=None, category=None, tagtype=None, **kwargs)[source]¶ Find script based on tag or category.
- Parameters
key (str, optional) – The tag key to search for.
category (str, optional) – The category of tag to search for. If not set, uncategorized tags will be searched.
tagtype (str, optional) – ‘type’ of Tag, by default this is either None (a normal Tag), alias or permission. This always apply to all queried tags.
kwargs (any) – Other optional parameter that may be supported by the manager method.
- Returns
- List of Scripts with tags matching
the search criteria, or an empty list if no matches were found.
- Return type
matches (list)
-
evennia.utils.search.search_account_tag(key=None, category=None, tagtype=None, **kwargs)[source]¶ Find account based on tag or category.
- Parameters
key (str, optional) – The tag key to search for.
category (str, optional) – The category of tag to search for. If not set, uncategorized tags will be searched.
tagtype (str, optional) – ‘type’ of Tag, by default this is either None (a normal Tag), alias or permission. This always apply to all queried tags.
kwargs (any) – Other optional parameter that may be supported by the manager method.
- Returns
- List of Accounts with tags matching
the search criteria, or an empty list if no matches were found.
- Return type
matches (list)
-
evennia.utils.search.search_channel_tag(key=None, category=None, tagtype=None, **kwargs)[source]¶ Find channel based on tag or category.
- Parameters
key (str, optional) – The tag key to search for.
category (str, optional) – The category of tag to search for. If not set, uncategorized tags will be searched.
tagtype (str, optional) – ‘type’ of Tag, by default this is either None (a normal Tag), alias or permission. This always apply to all queried tags.
kwargs (any) – Other optional parameter that may be supported by the manager method.
- Returns
- List of Channels with tags matching
the search criteria, or an empty list if no matches were found.
- Return type
matches (list)
evennia.utils.test_resources module¶
Various helper resources for writing unittests.
-
class
evennia.utils.test_resources.EvenniaTest(methodName='runTest')[source]¶ Bases:
django.test.testcases.TestCaseBase test for Evennia, sets up a basic environment.
-
account_typeclass¶
-
character_typeclass¶
-
exit_typeclass¶ alias of
evennia.objects.objects.DefaultExit
-
object_typeclass¶
-
room_typeclass¶ alias of
evennia.objects.objects.DefaultRoom
-
script_typeclass¶
-
-
class
evennia.utils.test_resources.LocalEvenniaTest(methodName='runTest')[source]¶ Bases:
evennia.utils.test_resources.EvenniaTestThis test class is intended for inheriting in mygame tests. It helps ensure your tests are run with your own objects.
-
account_typeclass= 'typeclasses.accounts.Account'¶
-
character_typeclass= 'typeclasses.characters.Character'¶
-
exit_typeclass= 'typeclasses.exits.Exit'¶
-
object_typeclass= 'typeclasses.objects.Object'¶
-
room_typeclass= 'typeclasses.rooms.Room'¶
-
script_typeclass= 'typeclasses.scripts.Script'¶
-
-
evennia.utils.test_resources._mock_deferlater(reactor, timedelay, callback, *args, **kwargs)[source]¶
-
evennia.utils.test_resources.unload_module(module)[source]¶ Reset import so one can mock global constants.
- Parameters
module (module, object or str) – The module will be removed so it will have to be imported again. If given an object, the module in which that object sits will be unloaded. A string should directly give the module pathname to unload.
Example
# (in a test method) unload_module(foo) with mock.patch(“foo.GLOBALTHING”, “mockval”):
import foo … # test code using foo.GLOBALTHING, now set to ‘mockval’
This allows for mocking constants global to the module, since otherwise those would not be mocked (since a module is only loaded once).
evennia.utils.text2html module¶
ANSI -> html converter
Credit for original idea and implementation goes to Muhammad Alkarouri and his snippet #577349 on http://code.activestate.com.
(extensively modified by Griatch 2010)
-
class
evennia.utils.text2html.TextToHTMLparser[source]¶ Bases:
objectThis class describes a parser for converting from ANSI to html.
-
bg_colormap= {'\x1b[1m\x1b[40m': 'bgcolor-008', '\x1b[1m\x1b[41m': 'bgcolor-009', '\x1b[1m\x1b[42m': 'bgcolor-010', '\x1b[1m\x1b[43m': 'bgcolor-011', '\x1b[1m\x1b[44m': 'bgcolor-012', '\x1b[1m\x1b[45m': 'bgcolor-013', '\x1b[1m\x1b[46m': 'bgcolor-014', '\x1b[1m\x1b[47m': 'bgcolor-015', '\x1b[40m': 'bgcolor-000', '\x1b[41m': 'bgcolor-001', '\x1b[42m': 'bgcolor-002', '\x1b[43m': 'bgcolor-003', '\x1b[44m': 'bgcolor-004', '\x1b[45m': 'bgcolor-005', '\x1b[46m': 'bgcolor-006', '\x1b[47m': 'bgcolor-007', '\x1b[48;5;100m': 'bgcolor-100', '\x1b[48;5;101m': 'bgcolor-101', '\x1b[48;5;102m': 'bgcolor-102', '\x1b[48;5;103m': 'bgcolor-103', '\x1b[48;5;104m': 'bgcolor-104', '\x1b[48;5;105m': 'bgcolor-105', '\x1b[48;5;106m': 'bgcolor-106', '\x1b[48;5;107m': 'bgcolor-107', '\x1b[48;5;108m': 'bgcolor-108', '\x1b[48;5;109m': 'bgcolor-109', '\x1b[48;5;110m': 'bgcolor-110', '\x1b[48;5;111m': 'bgcolor-111', '\x1b[48;5;112m': 'bgcolor-112', '\x1b[48;5;113m': 'bgcolor-113', '\x1b[48;5;114m': 'bgcolor-114', '\x1b[48;5;115m': 'bgcolor-115', '\x1b[48;5;116m': 'bgcolor-116', '\x1b[48;5;117m': 'bgcolor-117', '\x1b[48;5;118m': 'bgcolor-118', '\x1b[48;5;119m': 'bgcolor-119', '\x1b[48;5;120m': 'bgcolor-120', '\x1b[48;5;121m': 'bgcolor-121', '\x1b[48;5;122m': 'bgcolor-122', '\x1b[48;5;123m': 'bgcolor-123', '\x1b[48;5;124m': 'bgcolor-124', '\x1b[48;5;125m': 'bgcolor-125', '\x1b[48;5;126m': 'bgcolor-126', '\x1b[48;5;127m': 'bgcolor-127', '\x1b[48;5;128m': 'bgcolor-128', '\x1b[48;5;129m': 'bgcolor-129', '\x1b[48;5;130m': 'bgcolor-130', '\x1b[48;5;131m': 'bgcolor-131', '\x1b[48;5;132m': 'bgcolor-132', '\x1b[48;5;133m': 'bgcolor-133', '\x1b[48;5;134m': 'bgcolor-134', '\x1b[48;5;135m': 'bgcolor-135', '\x1b[48;5;136m': 'bgcolor-136', '\x1b[48;5;137m': 'bgcolor-137', '\x1b[48;5;138m': 'bgcolor-138', '\x1b[48;5;139m': 'bgcolor-139', '\x1b[48;5;140m': 'bgcolor-140', '\x1b[48;5;141m': 'bgcolor-141', '\x1b[48;5;142m': 'bgcolor-142', '\x1b[48;5;143m': 'bgcolor-143', '\x1b[48;5;144m': 'bgcolor-144', '\x1b[48;5;145m': 'bgcolor-145', '\x1b[48;5;146m': 'bgcolor-146', '\x1b[48;5;147m': 'bgcolor-147', '\x1b[48;5;148m': 'bgcolor-148', '\x1b[48;5;149m': 'bgcolor-149', '\x1b[48;5;150m': 'bgcolor-150', '\x1b[48;5;151m': 'bgcolor-151', '\x1b[48;5;152m': 'bgcolor-152', '\x1b[48;5;153m': 'bgcolor-153', '\x1b[48;5;154m': 'bgcolor-154', '\x1b[48;5;155m': 'bgcolor-155', '\x1b[48;5;156m': 'bgcolor-156', '\x1b[48;5;157m': 'bgcolor-157', '\x1b[48;5;158m': 'bgcolor-158', '\x1b[48;5;159m': 'bgcolor-159', '\x1b[48;5;160m': 'bgcolor-160', '\x1b[48;5;161m': 'bgcolor-161', '\x1b[48;5;162m': 'bgcolor-162', '\x1b[48;5;163m': 'bgcolor-163', '\x1b[48;5;164m': 'bgcolor-164', '\x1b[48;5;165m': 'bgcolor-165', '\x1b[48;5;166m': 'bgcolor-166', '\x1b[48;5;167m': 'bgcolor-167', '\x1b[48;5;168m': 'bgcolor-168', '\x1b[48;5;169m': 'bgcolor-169', '\x1b[48;5;16m': 'bgcolor-016', '\x1b[48;5;170m': 'bgcolor-170', '\x1b[48;5;171m': 'bgcolor-171', '\x1b[48;5;172m': 'bgcolor-172', '\x1b[48;5;173m': 'bgcolor-173', '\x1b[48;5;174m': 'bgcolor-174', '\x1b[48;5;175m': 'bgcolor-175', '\x1b[48;5;176m': 'bgcolor-176', '\x1b[48;5;177m': 'bgcolor-177', '\x1b[48;5;178m': 'bgcolor-178', '\x1b[48;5;179m': 'bgcolor-179', '\x1b[48;5;17m': 'bgcolor-017', '\x1b[48;5;180m': 'bgcolor-180', '\x1b[48;5;181m': 'bgcolor-181', '\x1b[48;5;182m': 'bgcolor-182', '\x1b[48;5;183m': 'bgcolor-183', '\x1b[48;5;184m': 'bgcolor-184', '\x1b[48;5;185m': 'bgcolor-185', '\x1b[48;5;186m': 'bgcolor-186', '\x1b[48;5;187m': 'bgcolor-187', '\x1b[48;5;188m': 'bgcolor-188', '\x1b[48;5;189m': 'bgcolor-189', '\x1b[48;5;18m': 'bgcolor-018', '\x1b[48;5;190m': 'bgcolor-190', '\x1b[48;5;191m': 'bgcolor-191', '\x1b[48;5;192m': 'bgcolor-192', '\x1b[48;5;193m': 'bgcolor-193', '\x1b[48;5;194m': 'bgcolor-194', '\x1b[48;5;195m': 'bgcolor-195', '\x1b[48;5;196m': 'bgcolor-196', '\x1b[48;5;197m': 'bgcolor-197', '\x1b[48;5;198m': 'bgcolor-198', '\x1b[48;5;199m': 'bgcolor-199', '\x1b[48;5;19m': 'bgcolor-019', '\x1b[48;5;200m': 'bgcolor-200', '\x1b[48;5;201m': 'bgcolor-201', '\x1b[48;5;202m': 'bgcolor-202', '\x1b[48;5;203m': 'bgcolor-203', '\x1b[48;5;204m': 'bgcolor-204', '\x1b[48;5;205m': 'bgcolor-205', '\x1b[48;5;206m': 'bgcolor-206', '\x1b[48;5;207m': 'bgcolor-207', '\x1b[48;5;208m': 'bgcolor-208', '\x1b[48;5;209m': 'bgcolor-209', '\x1b[48;5;20m': 'bgcolor-020', '\x1b[48;5;210m': 'bgcolor-210', '\x1b[48;5;211m': 'bgcolor-211', '\x1b[48;5;212m': 'bgcolor-212', '\x1b[48;5;213m': 'bgcolor-213', '\x1b[48;5;214m': 'bgcolor-214', '\x1b[48;5;215m': 'bgcolor-215', '\x1b[48;5;216m': 'bgcolor-216', '\x1b[48;5;217m': 'bgcolor-217', '\x1b[48;5;218m': 'bgcolor-218', '\x1b[48;5;219m': 'bgcolor-219', '\x1b[48;5;21m': 'bgcolor-021', '\x1b[48;5;220m': 'bgcolor-220', '\x1b[48;5;221m': 'bgcolor-221', '\x1b[48;5;222m': 'bgcolor-222', '\x1b[48;5;223m': 'bgcolor-223', '\x1b[48;5;224m': 'bgcolor-224', '\x1b[48;5;225m': 'bgcolor-225', '\x1b[48;5;226m': 'bgcolor-226', '\x1b[48;5;227m': 'bgcolor-227', '\x1b[48;5;228m': 'bgcolor-228', '\x1b[48;5;229m': 'bgcolor-229', '\x1b[48;5;22m': 'bgcolor-022', '\x1b[48;5;230m': 'bgcolor-230', '\x1b[48;5;231m': 'bgcolor-231', '\x1b[48;5;232m': 'bgcolor-232', '\x1b[48;5;233m': 'bgcolor-233', '\x1b[48;5;234m': 'bgcolor-234', '\x1b[48;5;235m': 'bgcolor-235', '\x1b[48;5;236m': 'bgcolor-236', '\x1b[48;5;237m': 'bgcolor-237', '\x1b[48;5;238m': 'bgcolor-238', '\x1b[48;5;239m': 'bgcolor-239', '\x1b[48;5;23m': 'bgcolor-023', '\x1b[48;5;240m': 'bgcolor-240', '\x1b[48;5;241m': 'bgcolor-241', '\x1b[48;5;242m': 'bgcolor-242', '\x1b[48;5;243m': 'bgcolor-243', '\x1b[48;5;244m': 'bgcolor-244', '\x1b[48;5;245m': 'bgcolor-245', '\x1b[48;5;246m': 'bgcolor-246', '\x1b[48;5;247m': 'bgcolor-247', '\x1b[48;5;248m': 'bgcolor-248', '\x1b[48;5;249m': 'bgcolor-249', '\x1b[48;5;24m': 'bgcolor-024', '\x1b[48;5;250m': 'bgcolor-250', '\x1b[48;5;251m': 'bgcolor-251', '\x1b[48;5;252m': 'bgcolor-252', '\x1b[48;5;253m': 'bgcolor-253', '\x1b[48;5;254m': 'bgcolor-254', '\x1b[48;5;255m': 'bgcolor-255', '\x1b[48;5;25m': 'bgcolor-025', '\x1b[48;5;26m': 'bgcolor-026', '\x1b[48;5;27m': 'bgcolor-027', '\x1b[48;5;28m': 'bgcolor-028', '\x1b[48;5;29m': 'bgcolor-029', '\x1b[48;5;30m': 'bgcolor-030', '\x1b[48;5;31m': 'bgcolor-031', '\x1b[48;5;32m': 'bgcolor-032', '\x1b[48;5;33m': 'bgcolor-033', '\x1b[48;5;34m': 'bgcolor-034', '\x1b[48;5;35m': 'bgcolor-035', '\x1b[48;5;36m': 'bgcolor-036', '\x1b[48;5;37m': 'bgcolor-037', '\x1b[48;5;38m': 'bgcolor-038', '\x1b[48;5;39m': 'bgcolor-039', '\x1b[48;5;40m': 'bgcolor-040', '\x1b[48;5;41m': 'bgcolor-041', '\x1b[48;5;42m': 'bgcolor-042', '\x1b[48;5;43m': 'bgcolor-043', '\x1b[48;5;44m': 'bgcolor-044', '\x1b[48;5;45m': 'bgcolor-045', '\x1b[48;5;46m': 'bgcolor-046', '\x1b[48;5;47m': 'bgcolor-047', '\x1b[48;5;48m': 'bgcolor-048', '\x1b[48;5;49m': 'bgcolor-049', '\x1b[48;5;50m': 'bgcolor-050', '\x1b[48;5;51m': 'bgcolor-051', '\x1b[48;5;52m': 'bgcolor-052', '\x1b[48;5;53m': 'bgcolor-053', '\x1b[48;5;54m': 'bgcolor-054', '\x1b[48;5;55m': 'bgcolor-055', '\x1b[48;5;56m': 'bgcolor-056', '\x1b[48;5;57m': 'bgcolor-057', '\x1b[48;5;58m': 'bgcolor-058', '\x1b[48;5;59m': 'bgcolor-059', '\x1b[48;5;60m': 'bgcolor-060', '\x1b[48;5;61m': 'bgcolor-061', '\x1b[48;5;62m': 'bgcolor-062', '\x1b[48;5;63m': 'bgcolor-063', '\x1b[48;5;64m': 'bgcolor-064', '\x1b[48;5;65m': 'bgcolor-065', '\x1b[48;5;66m': 'bgcolor-066', '\x1b[48;5;67m': 'bgcolor-067', '\x1b[48;5;68m': 'bgcolor-068', '\x1b[48;5;69m': 'bgcolor-069', '\x1b[48;5;70m': 'bgcolor-070', '\x1b[48;5;71m': 'bgcolor-071', '\x1b[48;5;72m': 'bgcolor-072', '\x1b[48;5;73m': 'bgcolor-073', '\x1b[48;5;74m': 'bgcolor-074', '\x1b[48;5;75m': 'bgcolor-075', '\x1b[48;5;76m': 'bgcolor-076', '\x1b[48;5;77m': 'bgcolor-077', '\x1b[48;5;78m': 'bgcolor-078', '\x1b[48;5;79m': 'bgcolor-079', '\x1b[48;5;80m': 'bgcolor-080', '\x1b[48;5;81m': 'bgcolor-081', '\x1b[48;5;82m': 'bgcolor-082', '\x1b[48;5;83m': 'bgcolor-083', '\x1b[48;5;84m': 'bgcolor-084', '\x1b[48;5;85m': 'bgcolor-085', '\x1b[48;5;86m': 'bgcolor-086', '\x1b[48;5;87m': 'bgcolor-087', '\x1b[48;5;88m': 'bgcolor-088', '\x1b[48;5;89m': 'bgcolor-089', '\x1b[48;5;90m': 'bgcolor-090', '\x1b[48;5;91m': 'bgcolor-091', '\x1b[48;5;92m': 'bgcolor-092', '\x1b[48;5;93m': 'bgcolor-093', '\x1b[48;5;94m': 'bgcolor-094', '\x1b[48;5;95m': 'bgcolor-095', '\x1b[48;5;96m': 'bgcolor-096', '\x1b[48;5;97m': 'bgcolor-097', '\x1b[48;5;98m': 'bgcolor-098', '\x1b[48;5;99m': 'bgcolor-099'}¶
-
bgfgstart= '((?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m)(\\s*)((?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[[3-4][0-8].*?m){0,1}'¶
-
bgfgstop= '(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m(\\s*)(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m|\x1b\\[0m|$'¶
-
bgstart= '((?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m)'¶
-
bgstop= '(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m|$'¶
-
blink= '\x1b[5m'¶
-
colorback= [('bgcolor-000', '\x1b[40m'), ('bgcolor-001', '\x1b[41m'), ('bgcolor-002', '\x1b[42m'), ('bgcolor-003', '\x1b[43m'), ('bgcolor-004', '\x1b[44m'), ('bgcolor-005', '\x1b[45m'), ('bgcolor-006', '\x1b[46m'), ('bgcolor-007', '\x1b[47m'), ('bgcolor-008', '\x1b[1m\x1b[40m'), ('bgcolor-009', '\x1b[1m\x1b[41m'), ('bgcolor-010', '\x1b[1m\x1b[42m'), ('bgcolor-011', '\x1b[1m\x1b[43m'), ('bgcolor-012', '\x1b[1m\x1b[44m'), ('bgcolor-013', '\x1b[1m\x1b[45m'), ('bgcolor-014', '\x1b[1m\x1b[46m'), ('bgcolor-015', '\x1b[1m\x1b[47m'), ('bgcolor-016', '\x1b[48;5;16m'), ('bgcolor-017', '\x1b[48;5;17m'), ('bgcolor-018', '\x1b[48;5;18m'), ('bgcolor-019', '\x1b[48;5;19m'), ('bgcolor-020', '\x1b[48;5;20m'), ('bgcolor-021', '\x1b[48;5;21m'), ('bgcolor-022', '\x1b[48;5;22m'), ('bgcolor-023', '\x1b[48;5;23m'), ('bgcolor-024', '\x1b[48;5;24m'), ('bgcolor-025', '\x1b[48;5;25m'), ('bgcolor-026', '\x1b[48;5;26m'), ('bgcolor-027', '\x1b[48;5;27m'), ('bgcolor-028', '\x1b[48;5;28m'), ('bgcolor-029', '\x1b[48;5;29m'), ('bgcolor-030', '\x1b[48;5;30m'), ('bgcolor-031', '\x1b[48;5;31m'), ('bgcolor-032', '\x1b[48;5;32m'), ('bgcolor-033', '\x1b[48;5;33m'), ('bgcolor-034', '\x1b[48;5;34m'), ('bgcolor-035', '\x1b[48;5;35m'), ('bgcolor-036', '\x1b[48;5;36m'), ('bgcolor-037', '\x1b[48;5;37m'), ('bgcolor-038', '\x1b[48;5;38m'), ('bgcolor-039', '\x1b[48;5;39m'), ('bgcolor-040', '\x1b[48;5;40m'), ('bgcolor-041', '\x1b[48;5;41m'), ('bgcolor-042', '\x1b[48;5;42m'), ('bgcolor-043', '\x1b[48;5;43m'), ('bgcolor-044', '\x1b[48;5;44m'), ('bgcolor-045', '\x1b[48;5;45m'), ('bgcolor-046', '\x1b[48;5;46m'), ('bgcolor-047', '\x1b[48;5;47m'), ('bgcolor-048', '\x1b[48;5;48m'), ('bgcolor-049', '\x1b[48;5;49m'), ('bgcolor-050', '\x1b[48;5;50m'), ('bgcolor-051', '\x1b[48;5;51m'), ('bgcolor-052', '\x1b[48;5;52m'), ('bgcolor-053', '\x1b[48;5;53m'), ('bgcolor-054', '\x1b[48;5;54m'), ('bgcolor-055', '\x1b[48;5;55m'), ('bgcolor-056', '\x1b[48;5;56m'), ('bgcolor-057', '\x1b[48;5;57m'), ('bgcolor-058', '\x1b[48;5;58m'), ('bgcolor-059', '\x1b[48;5;59m'), ('bgcolor-060', '\x1b[48;5;60m'), ('bgcolor-061', '\x1b[48;5;61m'), ('bgcolor-062', '\x1b[48;5;62m'), ('bgcolor-063', '\x1b[48;5;63m'), ('bgcolor-064', '\x1b[48;5;64m'), ('bgcolor-065', '\x1b[48;5;65m'), ('bgcolor-066', '\x1b[48;5;66m'), ('bgcolor-067', '\x1b[48;5;67m'), ('bgcolor-068', '\x1b[48;5;68m'), ('bgcolor-069', '\x1b[48;5;69m'), ('bgcolor-070', '\x1b[48;5;70m'), ('bgcolor-071', '\x1b[48;5;71m'), ('bgcolor-072', '\x1b[48;5;72m'), ('bgcolor-073', '\x1b[48;5;73m'), ('bgcolor-074', '\x1b[48;5;74m'), ('bgcolor-075', '\x1b[48;5;75m'), ('bgcolor-076', '\x1b[48;5;76m'), ('bgcolor-077', '\x1b[48;5;77m'), ('bgcolor-078', '\x1b[48;5;78m'), ('bgcolor-079', '\x1b[48;5;79m'), ('bgcolor-080', '\x1b[48;5;80m'), ('bgcolor-081', '\x1b[48;5;81m'), ('bgcolor-082', '\x1b[48;5;82m'), ('bgcolor-083', '\x1b[48;5;83m'), ('bgcolor-084', '\x1b[48;5;84m'), ('bgcolor-085', '\x1b[48;5;85m'), ('bgcolor-086', '\x1b[48;5;86m'), ('bgcolor-087', '\x1b[48;5;87m'), ('bgcolor-088', '\x1b[48;5;88m'), ('bgcolor-089', '\x1b[48;5;89m'), ('bgcolor-090', '\x1b[48;5;90m'), ('bgcolor-091', '\x1b[48;5;91m'), ('bgcolor-092', '\x1b[48;5;92m'), ('bgcolor-093', '\x1b[48;5;93m'), ('bgcolor-094', '\x1b[48;5;94m'), ('bgcolor-095', '\x1b[48;5;95m'), ('bgcolor-096', '\x1b[48;5;96m'), ('bgcolor-097', '\x1b[48;5;97m'), ('bgcolor-098', '\x1b[48;5;98m'), ('bgcolor-099', '\x1b[48;5;99m'), ('bgcolor-100', '\x1b[48;5;100m'), ('bgcolor-101', '\x1b[48;5;101m'), ('bgcolor-102', '\x1b[48;5;102m'), ('bgcolor-103', '\x1b[48;5;103m'), ('bgcolor-104', '\x1b[48;5;104m'), ('bgcolor-105', '\x1b[48;5;105m'), ('bgcolor-106', '\x1b[48;5;106m'), ('bgcolor-107', '\x1b[48;5;107m'), ('bgcolor-108', '\x1b[48;5;108m'), ('bgcolor-109', '\x1b[48;5;109m'), ('bgcolor-110', '\x1b[48;5;110m'), ('bgcolor-111', '\x1b[48;5;111m'), ('bgcolor-112', '\x1b[48;5;112m'), ('bgcolor-113', '\x1b[48;5;113m'), ('bgcolor-114', '\x1b[48;5;114m'), ('bgcolor-115', '\x1b[48;5;115m'), ('bgcolor-116', '\x1b[48;5;116m'), ('bgcolor-117', '\x1b[48;5;117m'), ('bgcolor-118', '\x1b[48;5;118m'), ('bgcolor-119', '\x1b[48;5;119m'), ('bgcolor-120', '\x1b[48;5;120m'), ('bgcolor-121', '\x1b[48;5;121m'), ('bgcolor-122', '\x1b[48;5;122m'), ('bgcolor-123', '\x1b[48;5;123m'), ('bgcolor-124', '\x1b[48;5;124m'), ('bgcolor-125', '\x1b[48;5;125m'), ('bgcolor-126', '\x1b[48;5;126m'), ('bgcolor-127', '\x1b[48;5;127m'), ('bgcolor-128', '\x1b[48;5;128m'), ('bgcolor-129', '\x1b[48;5;129m'), ('bgcolor-130', '\x1b[48;5;130m'), ('bgcolor-131', '\x1b[48;5;131m'), ('bgcolor-132', '\x1b[48;5;132m'), ('bgcolor-133', '\x1b[48;5;133m'), ('bgcolor-134', '\x1b[48;5;134m'), ('bgcolor-135', '\x1b[48;5;135m'), ('bgcolor-136', '\x1b[48;5;136m'), ('bgcolor-137', '\x1b[48;5;137m'), ('bgcolor-138', '\x1b[48;5;138m'), ('bgcolor-139', '\x1b[48;5;139m'), ('bgcolor-140', '\x1b[48;5;140m'), ('bgcolor-141', '\x1b[48;5;141m'), ('bgcolor-142', '\x1b[48;5;142m'), ('bgcolor-143', '\x1b[48;5;143m'), ('bgcolor-144', '\x1b[48;5;144m'), ('bgcolor-145', '\x1b[48;5;145m'), ('bgcolor-146', '\x1b[48;5;146m'), ('bgcolor-147', '\x1b[48;5;147m'), ('bgcolor-148', '\x1b[48;5;148m'), ('bgcolor-149', '\x1b[48;5;149m'), ('bgcolor-150', '\x1b[48;5;150m'), ('bgcolor-151', '\x1b[48;5;151m'), ('bgcolor-152', '\x1b[48;5;152m'), ('bgcolor-153', '\x1b[48;5;153m'), ('bgcolor-154', '\x1b[48;5;154m'), ('bgcolor-155', '\x1b[48;5;155m'), ('bgcolor-156', '\x1b[48;5;156m'), ('bgcolor-157', '\x1b[48;5;157m'), ('bgcolor-158', '\x1b[48;5;158m'), ('bgcolor-159', '\x1b[48;5;159m'), ('bgcolor-160', '\x1b[48;5;160m'), ('bgcolor-161', '\x1b[48;5;161m'), ('bgcolor-162', '\x1b[48;5;162m'), ('bgcolor-163', '\x1b[48;5;163m'), ('bgcolor-164', '\x1b[48;5;164m'), ('bgcolor-165', '\x1b[48;5;165m'), ('bgcolor-166', '\x1b[48;5;166m'), ('bgcolor-167', '\x1b[48;5;167m'), ('bgcolor-168', '\x1b[48;5;168m'), ('bgcolor-169', '\x1b[48;5;169m'), ('bgcolor-170', '\x1b[48;5;170m'), ('bgcolor-171', '\x1b[48;5;171m'), ('bgcolor-172', '\x1b[48;5;172m'), ('bgcolor-173', '\x1b[48;5;173m'), ('bgcolor-174', '\x1b[48;5;174m'), ('bgcolor-175', '\x1b[48;5;175m'), ('bgcolor-176', '\x1b[48;5;176m'), ('bgcolor-177', '\x1b[48;5;177m'), ('bgcolor-178', '\x1b[48;5;178m'), ('bgcolor-179', '\x1b[48;5;179m'), ('bgcolor-180', '\x1b[48;5;180m'), ('bgcolor-181', '\x1b[48;5;181m'), ('bgcolor-182', '\x1b[48;5;182m'), ('bgcolor-183', '\x1b[48;5;183m'), ('bgcolor-184', '\x1b[48;5;184m'), ('bgcolor-185', '\x1b[48;5;185m'), ('bgcolor-186', '\x1b[48;5;186m'), ('bgcolor-187', '\x1b[48;5;187m'), ('bgcolor-188', '\x1b[48;5;188m'), ('bgcolor-189', '\x1b[48;5;189m'), ('bgcolor-190', '\x1b[48;5;190m'), ('bgcolor-191', '\x1b[48;5;191m'), ('bgcolor-192', '\x1b[48;5;192m'), ('bgcolor-193', '\x1b[48;5;193m'), ('bgcolor-194', '\x1b[48;5;194m'), ('bgcolor-195', '\x1b[48;5;195m'), ('bgcolor-196', '\x1b[48;5;196m'), ('bgcolor-197', '\x1b[48;5;197m'), ('bgcolor-198', '\x1b[48;5;198m'), ('bgcolor-199', '\x1b[48;5;199m'), ('bgcolor-200', '\x1b[48;5;200m'), ('bgcolor-201', '\x1b[48;5;201m'), ('bgcolor-202', '\x1b[48;5;202m'), ('bgcolor-203', '\x1b[48;5;203m'), ('bgcolor-204', '\x1b[48;5;204m'), ('bgcolor-205', '\x1b[48;5;205m'), ('bgcolor-206', '\x1b[48;5;206m'), ('bgcolor-207', '\x1b[48;5;207m'), ('bgcolor-208', '\x1b[48;5;208m'), ('bgcolor-209', '\x1b[48;5;209m'), ('bgcolor-210', '\x1b[48;5;210m'), ('bgcolor-211', '\x1b[48;5;211m'), ('bgcolor-212', '\x1b[48;5;212m'), ('bgcolor-213', '\x1b[48;5;213m'), ('bgcolor-214', '\x1b[48;5;214m'), ('bgcolor-215', '\x1b[48;5;215m'), ('bgcolor-216', '\x1b[48;5;216m'), ('bgcolor-217', '\x1b[48;5;217m'), ('bgcolor-218', '\x1b[48;5;218m'), ('bgcolor-219', '\x1b[48;5;219m'), ('bgcolor-220', '\x1b[48;5;220m'), ('bgcolor-221', '\x1b[48;5;221m'), ('bgcolor-222', '\x1b[48;5;222m'), ('bgcolor-223', '\x1b[48;5;223m'), ('bgcolor-224', '\x1b[48;5;224m'), ('bgcolor-225', '\x1b[48;5;225m'), ('bgcolor-226', '\x1b[48;5;226m'), ('bgcolor-227', '\x1b[48;5;227m'), ('bgcolor-228', '\x1b[48;5;228m'), ('bgcolor-229', '\x1b[48;5;229m'), ('bgcolor-230', '\x1b[48;5;230m'), ('bgcolor-231', '\x1b[48;5;231m'), ('bgcolor-232', '\x1b[48;5;232m'), ('bgcolor-233', '\x1b[48;5;233m'), ('bgcolor-234', '\x1b[48;5;234m'), ('bgcolor-235', '\x1b[48;5;235m'), ('bgcolor-236', '\x1b[48;5;236m'), ('bgcolor-237', '\x1b[48;5;237m'), ('bgcolor-238', '\x1b[48;5;238m'), ('bgcolor-239', '\x1b[48;5;239m'), ('bgcolor-240', '\x1b[48;5;240m'), ('bgcolor-241', '\x1b[48;5;241m'), ('bgcolor-242', '\x1b[48;5;242m'), ('bgcolor-243', '\x1b[48;5;243m'), ('bgcolor-244', '\x1b[48;5;244m'), ('bgcolor-245', '\x1b[48;5;245m'), ('bgcolor-246', '\x1b[48;5;246m'), ('bgcolor-247', '\x1b[48;5;247m'), ('bgcolor-248', '\x1b[48;5;248m'), ('bgcolor-249', '\x1b[48;5;249m'), ('bgcolor-250', '\x1b[48;5;250m'), ('bgcolor-251', '\x1b[48;5;251m'), ('bgcolor-252', '\x1b[48;5;252m'), ('bgcolor-253', '\x1b[48;5;253m'), ('bgcolor-254', '\x1b[48;5;254m'), ('bgcolor-255', '\x1b[48;5;255m')]¶
-
colorcodes= [('color-000', '\x1b[22m\x1b[30m'), ('color-001', '\x1b[22m\x1b[31m'), ('color-002', '\x1b[22m\x1b[32m'), ('color-003', '\x1b[22m\x1b[33m'), ('color-004', '\x1b[22m\x1b[34m'), ('color-005', '\x1b[22m\x1b[35m'), ('color-006', '\x1b[22m\x1b[36m'), ('color-007', '\x1b[22m\x1b[37m'), ('color-008', '\x1b[1m\x1b[30m'), ('color-009', '\x1b[1m\x1b[31m'), ('color-010', '\x1b[1m\x1b[32m'), ('color-011', '\x1b[1m\x1b[33m'), ('color-012', '\x1b[1m\x1b[34m'), ('color-013', '\x1b[1m\x1b[35m'), ('color-014', '\x1b[1m\x1b[36m'), ('color-015', '\x1b[1m\x1b[37m'), ('color-016', '\x1b[38;5;16m'), ('color-017', '\x1b[38;5;17m'), ('color-018', '\x1b[38;5;18m'), ('color-019', '\x1b[38;5;19m'), ('color-020', '\x1b[38;5;20m'), ('color-021', '\x1b[38;5;21m'), ('color-022', '\x1b[38;5;22m'), ('color-023', '\x1b[38;5;23m'), ('color-024', '\x1b[38;5;24m'), ('color-025', '\x1b[38;5;25m'), ('color-026', '\x1b[38;5;26m'), ('color-027', '\x1b[38;5;27m'), ('color-028', '\x1b[38;5;28m'), ('color-029', '\x1b[38;5;29m'), ('color-030', '\x1b[38;5;30m'), ('color-031', '\x1b[38;5;31m'), ('color-032', '\x1b[38;5;32m'), ('color-033', '\x1b[38;5;33m'), ('color-034', '\x1b[38;5;34m'), ('color-035', '\x1b[38;5;35m'), ('color-036', '\x1b[38;5;36m'), ('color-037', '\x1b[38;5;37m'), ('color-038', '\x1b[38;5;38m'), ('color-039', '\x1b[38;5;39m'), ('color-040', '\x1b[38;5;40m'), ('color-041', '\x1b[38;5;41m'), ('color-042', '\x1b[38;5;42m'), ('color-043', '\x1b[38;5;43m'), ('color-044', '\x1b[38;5;44m'), ('color-045', '\x1b[38;5;45m'), ('color-046', '\x1b[38;5;46m'), ('color-047', '\x1b[38;5;47m'), ('color-048', '\x1b[38;5;48m'), ('color-049', '\x1b[38;5;49m'), ('color-050', '\x1b[38;5;50m'), ('color-051', '\x1b[38;5;51m'), ('color-052', '\x1b[38;5;52m'), ('color-053', '\x1b[38;5;53m'), ('color-054', '\x1b[38;5;54m'), ('color-055', '\x1b[38;5;55m'), ('color-056', '\x1b[38;5;56m'), ('color-057', '\x1b[38;5;57m'), ('color-058', '\x1b[38;5;58m'), ('color-059', '\x1b[38;5;59m'), ('color-060', '\x1b[38;5;60m'), ('color-061', '\x1b[38;5;61m'), ('color-062', '\x1b[38;5;62m'), ('color-063', '\x1b[38;5;63m'), ('color-064', '\x1b[38;5;64m'), ('color-065', '\x1b[38;5;65m'), ('color-066', '\x1b[38;5;66m'), ('color-067', '\x1b[38;5;67m'), ('color-068', '\x1b[38;5;68m'), ('color-069', '\x1b[38;5;69m'), ('color-070', '\x1b[38;5;70m'), ('color-071', '\x1b[38;5;71m'), ('color-072', '\x1b[38;5;72m'), ('color-073', '\x1b[38;5;73m'), ('color-074', '\x1b[38;5;74m'), ('color-075', '\x1b[38;5;75m'), ('color-076', '\x1b[38;5;76m'), ('color-077', '\x1b[38;5;77m'), ('color-078', '\x1b[38;5;78m'), ('color-079', '\x1b[38;5;79m'), ('color-080', '\x1b[38;5;80m'), ('color-081', '\x1b[38;5;81m'), ('color-082', '\x1b[38;5;82m'), ('color-083', '\x1b[38;5;83m'), ('color-084', '\x1b[38;5;84m'), ('color-085', '\x1b[38;5;85m'), ('color-086', '\x1b[38;5;86m'), ('color-087', '\x1b[38;5;87m'), ('color-088', '\x1b[38;5;88m'), ('color-089', '\x1b[38;5;89m'), ('color-090', '\x1b[38;5;90m'), ('color-091', '\x1b[38;5;91m'), ('color-092', '\x1b[38;5;92m'), ('color-093', '\x1b[38;5;93m'), ('color-094', '\x1b[38;5;94m'), ('color-095', '\x1b[38;5;95m'), ('color-096', '\x1b[38;5;96m'), ('color-097', '\x1b[38;5;97m'), ('color-098', '\x1b[38;5;98m'), ('color-099', '\x1b[38;5;99m'), ('color-100', '\x1b[38;5;100m'), ('color-101', '\x1b[38;5;101m'), ('color-102', '\x1b[38;5;102m'), ('color-103', '\x1b[38;5;103m'), ('color-104', '\x1b[38;5;104m'), ('color-105', '\x1b[38;5;105m'), ('color-106', '\x1b[38;5;106m'), ('color-107', '\x1b[38;5;107m'), ('color-108', '\x1b[38;5;108m'), ('color-109', '\x1b[38;5;109m'), ('color-110', '\x1b[38;5;110m'), ('color-111', '\x1b[38;5;111m'), ('color-112', '\x1b[38;5;112m'), ('color-113', '\x1b[38;5;113m'), ('color-114', '\x1b[38;5;114m'), ('color-115', '\x1b[38;5;115m'), ('color-116', '\x1b[38;5;116m'), ('color-117', '\x1b[38;5;117m'), ('color-118', '\x1b[38;5;118m'), ('color-119', '\x1b[38;5;119m'), ('color-120', '\x1b[38;5;120m'), ('color-121', '\x1b[38;5;121m'), ('color-122', '\x1b[38;5;122m'), ('color-123', '\x1b[38;5;123m'), ('color-124', '\x1b[38;5;124m'), ('color-125', '\x1b[38;5;125m'), ('color-126', '\x1b[38;5;126m'), ('color-127', '\x1b[38;5;127m'), ('color-128', '\x1b[38;5;128m'), ('color-129', '\x1b[38;5;129m'), ('color-130', '\x1b[38;5;130m'), ('color-131', '\x1b[38;5;131m'), ('color-132', '\x1b[38;5;132m'), ('color-133', '\x1b[38;5;133m'), ('color-134', '\x1b[38;5;134m'), ('color-135', '\x1b[38;5;135m'), ('color-136', '\x1b[38;5;136m'), ('color-137', '\x1b[38;5;137m'), ('color-138', '\x1b[38;5;138m'), ('color-139', '\x1b[38;5;139m'), ('color-140', '\x1b[38;5;140m'), ('color-141', '\x1b[38;5;141m'), ('color-142', '\x1b[38;5;142m'), ('color-143', '\x1b[38;5;143m'), ('color-144', '\x1b[38;5;144m'), ('color-145', '\x1b[38;5;145m'), ('color-146', '\x1b[38;5;146m'), ('color-147', '\x1b[38;5;147m'), ('color-148', '\x1b[38;5;148m'), ('color-149', '\x1b[38;5;149m'), ('color-150', '\x1b[38;5;150m'), ('color-151', '\x1b[38;5;151m'), ('color-152', '\x1b[38;5;152m'), ('color-153', '\x1b[38;5;153m'), ('color-154', '\x1b[38;5;154m'), ('color-155', '\x1b[38;5;155m'), ('color-156', '\x1b[38;5;156m'), ('color-157', '\x1b[38;5;157m'), ('color-158', '\x1b[38;5;158m'), ('color-159', '\x1b[38;5;159m'), ('color-160', '\x1b[38;5;160m'), ('color-161', '\x1b[38;5;161m'), ('color-162', '\x1b[38;5;162m'), ('color-163', '\x1b[38;5;163m'), ('color-164', '\x1b[38;5;164m'), ('color-165', '\x1b[38;5;165m'), ('color-166', '\x1b[38;5;166m'), ('color-167', '\x1b[38;5;167m'), ('color-168', '\x1b[38;5;168m'), ('color-169', '\x1b[38;5;169m'), ('color-170', '\x1b[38;5;170m'), ('color-171', '\x1b[38;5;171m'), ('color-172', '\x1b[38;5;172m'), ('color-173', '\x1b[38;5;173m'), ('color-174', '\x1b[38;5;174m'), ('color-175', '\x1b[38;5;175m'), ('color-176', '\x1b[38;5;176m'), ('color-177', '\x1b[38;5;177m'), ('color-178', '\x1b[38;5;178m'), ('color-179', '\x1b[38;5;179m'), ('color-180', '\x1b[38;5;180m'), ('color-181', '\x1b[38;5;181m'), ('color-182', '\x1b[38;5;182m'), ('color-183', '\x1b[38;5;183m'), ('color-184', '\x1b[38;5;184m'), ('color-185', '\x1b[38;5;185m'), ('color-186', '\x1b[38;5;186m'), ('color-187', '\x1b[38;5;187m'), ('color-188', '\x1b[38;5;188m'), ('color-189', '\x1b[38;5;189m'), ('color-190', '\x1b[38;5;190m'), ('color-191', '\x1b[38;5;191m'), ('color-192', '\x1b[38;5;192m'), ('color-193', '\x1b[38;5;193m'), ('color-194', '\x1b[38;5;194m'), ('color-195', '\x1b[38;5;195m'), ('color-196', '\x1b[38;5;196m'), ('color-197', '\x1b[38;5;197m'), ('color-198', '\x1b[38;5;198m'), ('color-199', '\x1b[38;5;199m'), ('color-200', '\x1b[38;5;200m'), ('color-201', '\x1b[38;5;201m'), ('color-202', '\x1b[38;5;202m'), ('color-203', '\x1b[38;5;203m'), ('color-204', '\x1b[38;5;204m'), ('color-205', '\x1b[38;5;205m'), ('color-206', '\x1b[38;5;206m'), ('color-207', '\x1b[38;5;207m'), ('color-208', '\x1b[38;5;208m'), ('color-209', '\x1b[38;5;209m'), ('color-210', '\x1b[38;5;210m'), ('color-211', '\x1b[38;5;211m'), ('color-212', '\x1b[38;5;212m'), ('color-213', '\x1b[38;5;213m'), ('color-214', '\x1b[38;5;214m'), ('color-215', '\x1b[38;5;215m'), ('color-216', '\x1b[38;5;216m'), ('color-217', '\x1b[38;5;217m'), ('color-218', '\x1b[38;5;218m'), ('color-219', '\x1b[38;5;219m'), ('color-220', '\x1b[38;5;220m'), ('color-221', '\x1b[38;5;221m'), ('color-222', '\x1b[38;5;222m'), ('color-223', '\x1b[38;5;223m'), ('color-224', '\x1b[38;5;224m'), ('color-225', '\x1b[38;5;225m'), ('color-226', '\x1b[38;5;226m'), ('color-227', '\x1b[38;5;227m'), ('color-228', '\x1b[38;5;228m'), ('color-229', '\x1b[38;5;229m'), ('color-230', '\x1b[38;5;230m'), ('color-231', '\x1b[38;5;231m'), ('color-232', '\x1b[38;5;232m'), ('color-233', '\x1b[38;5;233m'), ('color-234', '\x1b[38;5;234m'), ('color-235', '\x1b[38;5;235m'), ('color-236', '\x1b[38;5;236m'), ('color-237', '\x1b[38;5;237m'), ('color-238', '\x1b[38;5;238m'), ('color-239', '\x1b[38;5;239m'), ('color-240', '\x1b[38;5;240m'), ('color-241', '\x1b[38;5;241m'), ('color-242', '\x1b[38;5;242m'), ('color-243', '\x1b[38;5;243m'), ('color-244', '\x1b[38;5;244m'), ('color-245', '\x1b[38;5;245m'), ('color-246', '\x1b[38;5;246m'), ('color-247', '\x1b[38;5;247m'), ('color-248', '\x1b[38;5;248m'), ('color-249', '\x1b[38;5;249m'), ('color-250', '\x1b[38;5;250m'), ('color-251', '\x1b[38;5;251m'), ('color-252', '\x1b[38;5;252m'), ('color-253', '\x1b[38;5;253m'), ('color-254', '\x1b[38;5;254m'), ('color-255', '\x1b[38;5;255m')]¶
-
convert_linebreaks(text)[source]¶ Extra method for cleaning linebreaks
- Parameters
text (str) – Text to process.
- Returns
Processed text.
- Return type
text (str)
-
convert_urls(text)[source]¶ Replace urls (http://…) by valid HTML.
- Parameters
text (str) – Text to process.
- Returns
Processed text.
- Return type
text (str)
-
fg_colormap= {'\x1b[1m\x1b[30m': 'color-008', '\x1b[1m\x1b[31m': 'color-009', '\x1b[1m\x1b[32m': 'color-010', '\x1b[1m\x1b[33m': 'color-011', '\x1b[1m\x1b[34m': 'color-012', '\x1b[1m\x1b[35m': 'color-013', '\x1b[1m\x1b[36m': 'color-014', '\x1b[1m\x1b[37m': 'color-015', '\x1b[22m\x1b[30m': 'color-000', '\x1b[22m\x1b[31m': 'color-001', '\x1b[22m\x1b[32m': 'color-002', '\x1b[22m\x1b[33m': 'color-003', '\x1b[22m\x1b[34m': 'color-004', '\x1b[22m\x1b[35m': 'color-005', '\x1b[22m\x1b[36m': 'color-006', '\x1b[22m\x1b[37m': 'color-007', '\x1b[38;5;100m': 'color-100', '\x1b[38;5;101m': 'color-101', '\x1b[38;5;102m': 'color-102', '\x1b[38;5;103m': 'color-103', '\x1b[38;5;104m': 'color-104', '\x1b[38;5;105m': 'color-105', '\x1b[38;5;106m': 'color-106', '\x1b[38;5;107m': 'color-107', '\x1b[38;5;108m': 'color-108', '\x1b[38;5;109m': 'color-109', '\x1b[38;5;110m': 'color-110', '\x1b[38;5;111m': 'color-111', '\x1b[38;5;112m': 'color-112', '\x1b[38;5;113m': 'color-113', '\x1b[38;5;114m': 'color-114', '\x1b[38;5;115m': 'color-115', '\x1b[38;5;116m': 'color-116', '\x1b[38;5;117m': 'color-117', '\x1b[38;5;118m': 'color-118', '\x1b[38;5;119m': 'color-119', '\x1b[38;5;120m': 'color-120', '\x1b[38;5;121m': 'color-121', '\x1b[38;5;122m': 'color-122', '\x1b[38;5;123m': 'color-123', '\x1b[38;5;124m': 'color-124', '\x1b[38;5;125m': 'color-125', '\x1b[38;5;126m': 'color-126', '\x1b[38;5;127m': 'color-127', '\x1b[38;5;128m': 'color-128', '\x1b[38;5;129m': 'color-129', '\x1b[38;5;130m': 'color-130', '\x1b[38;5;131m': 'color-131', '\x1b[38;5;132m': 'color-132', '\x1b[38;5;133m': 'color-133', '\x1b[38;5;134m': 'color-134', '\x1b[38;5;135m': 'color-135', '\x1b[38;5;136m': 'color-136', '\x1b[38;5;137m': 'color-137', '\x1b[38;5;138m': 'color-138', '\x1b[38;5;139m': 'color-139', '\x1b[38;5;140m': 'color-140', '\x1b[38;5;141m': 'color-141', '\x1b[38;5;142m': 'color-142', '\x1b[38;5;143m': 'color-143', '\x1b[38;5;144m': 'color-144', '\x1b[38;5;145m': 'color-145', '\x1b[38;5;146m': 'color-146', '\x1b[38;5;147m': 'color-147', '\x1b[38;5;148m': 'color-148', '\x1b[38;5;149m': 'color-149', '\x1b[38;5;150m': 'color-150', '\x1b[38;5;151m': 'color-151', '\x1b[38;5;152m': 'color-152', '\x1b[38;5;153m': 'color-153', '\x1b[38;5;154m': 'color-154', '\x1b[38;5;155m': 'color-155', '\x1b[38;5;156m': 'color-156', '\x1b[38;5;157m': 'color-157', '\x1b[38;5;158m': 'color-158', '\x1b[38;5;159m': 'color-159', '\x1b[38;5;160m': 'color-160', '\x1b[38;5;161m': 'color-161', '\x1b[38;5;162m': 'color-162', '\x1b[38;5;163m': 'color-163', '\x1b[38;5;164m': 'color-164', '\x1b[38;5;165m': 'color-165', '\x1b[38;5;166m': 'color-166', '\x1b[38;5;167m': 'color-167', '\x1b[38;5;168m': 'color-168', '\x1b[38;5;169m': 'color-169', '\x1b[38;5;16m': 'color-016', '\x1b[38;5;170m': 'color-170', '\x1b[38;5;171m': 'color-171', '\x1b[38;5;172m': 'color-172', '\x1b[38;5;173m': 'color-173', '\x1b[38;5;174m': 'color-174', '\x1b[38;5;175m': 'color-175', '\x1b[38;5;176m': 'color-176', '\x1b[38;5;177m': 'color-177', '\x1b[38;5;178m': 'color-178', '\x1b[38;5;179m': 'color-179', '\x1b[38;5;17m': 'color-017', '\x1b[38;5;180m': 'color-180', '\x1b[38;5;181m': 'color-181', '\x1b[38;5;182m': 'color-182', '\x1b[38;5;183m': 'color-183', '\x1b[38;5;184m': 'color-184', '\x1b[38;5;185m': 'color-185', '\x1b[38;5;186m': 'color-186', '\x1b[38;5;187m': 'color-187', '\x1b[38;5;188m': 'color-188', '\x1b[38;5;189m': 'color-189', '\x1b[38;5;18m': 'color-018', '\x1b[38;5;190m': 'color-190', '\x1b[38;5;191m': 'color-191', '\x1b[38;5;192m': 'color-192', '\x1b[38;5;193m': 'color-193', '\x1b[38;5;194m': 'color-194', '\x1b[38;5;195m': 'color-195', '\x1b[38;5;196m': 'color-196', '\x1b[38;5;197m': 'color-197', '\x1b[38;5;198m': 'color-198', '\x1b[38;5;199m': 'color-199', '\x1b[38;5;19m': 'color-019', '\x1b[38;5;200m': 'color-200', '\x1b[38;5;201m': 'color-201', '\x1b[38;5;202m': 'color-202', '\x1b[38;5;203m': 'color-203', '\x1b[38;5;204m': 'color-204', '\x1b[38;5;205m': 'color-205', '\x1b[38;5;206m': 'color-206', '\x1b[38;5;207m': 'color-207', '\x1b[38;5;208m': 'color-208', '\x1b[38;5;209m': 'color-209', '\x1b[38;5;20m': 'color-020', '\x1b[38;5;210m': 'color-210', '\x1b[38;5;211m': 'color-211', '\x1b[38;5;212m': 'color-212', '\x1b[38;5;213m': 'color-213', '\x1b[38;5;214m': 'color-214', '\x1b[38;5;215m': 'color-215', '\x1b[38;5;216m': 'color-216', '\x1b[38;5;217m': 'color-217', '\x1b[38;5;218m': 'color-218', '\x1b[38;5;219m': 'color-219', '\x1b[38;5;21m': 'color-021', '\x1b[38;5;220m': 'color-220', '\x1b[38;5;221m': 'color-221', '\x1b[38;5;222m': 'color-222', '\x1b[38;5;223m': 'color-223', '\x1b[38;5;224m': 'color-224', '\x1b[38;5;225m': 'color-225', '\x1b[38;5;226m': 'color-226', '\x1b[38;5;227m': 'color-227', '\x1b[38;5;228m': 'color-228', '\x1b[38;5;229m': 'color-229', '\x1b[38;5;22m': 'color-022', '\x1b[38;5;230m': 'color-230', '\x1b[38;5;231m': 'color-231', '\x1b[38;5;232m': 'color-232', '\x1b[38;5;233m': 'color-233', '\x1b[38;5;234m': 'color-234', '\x1b[38;5;235m': 'color-235', '\x1b[38;5;236m': 'color-236', '\x1b[38;5;237m': 'color-237', '\x1b[38;5;238m': 'color-238', '\x1b[38;5;239m': 'color-239', '\x1b[38;5;23m': 'color-023', '\x1b[38;5;240m': 'color-240', '\x1b[38;5;241m': 'color-241', '\x1b[38;5;242m': 'color-242', '\x1b[38;5;243m': 'color-243', '\x1b[38;5;244m': 'color-244', '\x1b[38;5;245m': 'color-245', '\x1b[38;5;246m': 'color-246', '\x1b[38;5;247m': 'color-247', '\x1b[38;5;248m': 'color-248', '\x1b[38;5;249m': 'color-249', '\x1b[38;5;24m': 'color-024', '\x1b[38;5;250m': 'color-250', '\x1b[38;5;251m': 'color-251', '\x1b[38;5;252m': 'color-252', '\x1b[38;5;253m': 'color-253', '\x1b[38;5;254m': 'color-254', '\x1b[38;5;255m': 'color-255', '\x1b[38;5;25m': 'color-025', '\x1b[38;5;26m': 'color-026', '\x1b[38;5;27m': 'color-027', '\x1b[38;5;28m': 'color-028', '\x1b[38;5;29m': 'color-029', '\x1b[38;5;30m': 'color-030', '\x1b[38;5;31m': 'color-031', '\x1b[38;5;32m': 'color-032', '\x1b[38;5;33m': 'color-033', '\x1b[38;5;34m': 'color-034', '\x1b[38;5;35m': 'color-035', '\x1b[38;5;36m': 'color-036', '\x1b[38;5;37m': 'color-037', '\x1b[38;5;38m': 'color-038', '\x1b[38;5;39m': 'color-039', '\x1b[38;5;40m': 'color-040', '\x1b[38;5;41m': 'color-041', '\x1b[38;5;42m': 'color-042', '\x1b[38;5;43m': 'color-043', '\x1b[38;5;44m': 'color-044', '\x1b[38;5;45m': 'color-045', '\x1b[38;5;46m': 'color-046', '\x1b[38;5;47m': 'color-047', '\x1b[38;5;48m': 'color-048', '\x1b[38;5;49m': 'color-049', '\x1b[38;5;50m': 'color-050', '\x1b[38;5;51m': 'color-051', '\x1b[38;5;52m': 'color-052', '\x1b[38;5;53m': 'color-053', '\x1b[38;5;54m': 'color-054', '\x1b[38;5;55m': 'color-055', '\x1b[38;5;56m': 'color-056', '\x1b[38;5;57m': 'color-057', '\x1b[38;5;58m': 'color-058', '\x1b[38;5;59m': 'color-059', '\x1b[38;5;60m': 'color-060', '\x1b[38;5;61m': 'color-061', '\x1b[38;5;62m': 'color-062', '\x1b[38;5;63m': 'color-063', '\x1b[38;5;64m': 'color-064', '\x1b[38;5;65m': 'color-065', '\x1b[38;5;66m': 'color-066', '\x1b[38;5;67m': 'color-067', '\x1b[38;5;68m': 'color-068', '\x1b[38;5;69m': 'color-069', '\x1b[38;5;70m': 'color-070', '\x1b[38;5;71m': 'color-071', '\x1b[38;5;72m': 'color-072', '\x1b[38;5;73m': 'color-073', '\x1b[38;5;74m': 'color-074', '\x1b[38;5;75m': 'color-075', '\x1b[38;5;76m': 'color-076', '\x1b[38;5;77m': 'color-077', '\x1b[38;5;78m': 'color-078', '\x1b[38;5;79m': 'color-079', '\x1b[38;5;80m': 'color-080', '\x1b[38;5;81m': 'color-081', '\x1b[38;5;82m': 'color-082', '\x1b[38;5;83m': 'color-083', '\x1b[38;5;84m': 'color-084', '\x1b[38;5;85m': 'color-085', '\x1b[38;5;86m': 'color-086', '\x1b[38;5;87m': 'color-087', '\x1b[38;5;88m': 'color-088', '\x1b[38;5;89m': 'color-089', '\x1b[38;5;90m': 'color-090', '\x1b[38;5;91m': 'color-091', '\x1b[38;5;92m': 'color-092', '\x1b[38;5;93m': 'color-093', '\x1b[38;5;94m': 'color-094', '\x1b[38;5;95m': 'color-095', '\x1b[38;5;96m': 'color-096', '\x1b[38;5;97m': 'color-097', '\x1b[38;5;98m': 'color-098', '\x1b[38;5;99m': 'color-099'}¶
-
fgstart= '((?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m)'¶
-
fgstop= '(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m|\x1b\\[0m|$'¶
-
hilite= '\x1b[1m'¶
-
inverse= '\x1b[7m'¶
-
normal= '\x1b[0m'¶
-
parse(text, strip_ansi=False)[source]¶ Main access function, converts a text containing ANSI codes into html statements.
- Parameters
text (str) – Text to process.
strip_ansi (bool, optional) –
- Returns
Parsed text.
- Return type
text (str)
-
re_bgfg= re.compile('((?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m)(\\s*)((?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[[3-4][0-8].*?m){0,1}(.*?)(?=(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m(\\s*)(?:\x1b\\[1m|\x1b\)¶
-
re_bgs= re.compile('((?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m)(.*?)(?=(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m|$)')¶
-
re_blink= re.compile('(?:\x1b\\[5m)(.*?)(?=(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m|\x1b\\[0m|$|(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m|$)')¶
-
re_blinking(text)[source]¶ Replace ansi blink with custom blink css class
- Parameters
text (str) – Text to process.
- Returns
Processed text.
- Return type
text (str)
-
re_bold(text)[source]¶ Clean out superfluous hilights rather than set <strong>to make it match the look of telnet.
- Parameters
text (str) – Text to process.
- Returns
Processed text.
- Return type
text (str)
-
re_color(text)[source]¶ Replace ansi colors with html color class names. Let the client choose how it will display colors, if it wishes to.
- Parameters
text (str) – the string with color to replace.
- Returns
Re-colored text.
- Return type
text (str)
-
re_dblspace= re.compile(' {2,}', re.MULTILINE)¶
-
re_double_space(text)[source]¶ HTML will swallow any normal space after the first, so if any slipped through we must make sure to replace them with ” ”
-
re_fgs= re.compile('((?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m)(.*?)(?=(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m|\x1b\\[0m|$)')¶
-
re_hilite= re.compile('(?:\x1b\\[1m)(.*)(?=(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m|\x1b\\[0m|$|(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m|$)')¶
-
re_inverse= re.compile('(?:\x1b\\[7m)(.*?)(?=(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m|\x1b\\[0m|$|(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m|$)')¶
-
re_inversing(text)[source]¶ Replace ansi inverse with custom inverse css class
- Parameters
text (str) – Text to process.
- Returns
Processed text.
- Return type
text (str)
-
re_mxplink= re.compile('\\|lc(.*?)\\|lt(.*?)\\|le', re.DOTALL)¶
-
re_normal= re.compile('\x1b\\[0m')¶
-
re_string= re.compile('(?P<htmlchars>[<&>])|(?P<firstspace>(?<=\\S) )|(?P<space> [ \\t]+)|(?P<spacestart>^ )|(?P<lineend>\\r\\n|\\r|\\n)', re.IGNORECASE|re.MULTILINE|re.DOTALL)¶
-
re_uline= re.compile('(?:\x1b\\[4m)(.*?)(?=(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m|\x1b\\[0m|$|(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m|$)')¶
-
re_underline(text)[source]¶ Replace ansi underline with html underline class name.
- Parameters
text (str) – Text to process.
- Returns
Processed text.
- Return type
text (str)
-
re_unhilite= re.compile('(?:\x1b\\[22m)(.*)(?=(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[3[0-8].*?m|\x1b\\[0m|$|(?:\x1b\\[1m|\x1b\\[22m){0,1}\x1b\\[4[0-8].*?m|\x1b\\[0m|$)')¶
-
re_url= re.compile('((?:ftp|www|https?)\\W+(?:(?!\\.(?:\\s|$)|&\\w+;)[^"\\\',;$*^\\\\(){}<>\\[\\]\\s])+)(\\.(?:\\s|$)|&\\w+;|)')¶
-
remove_backspaces(text)[source]¶ Removes special escape sequences
- Parameters
text (str) – Text to process.
- Returns
Processed text.
- Return type
text (str)
-
remove_bells(text)[source]¶ Remove ansi specials
- Parameters
text (str) – Text to process.
- Returns
Processed text.
- Return type
text (str)
-
sub_mxp_links(match)[source]¶ Helper method to be passed to re.sub, replaces MXP links with HTML code.
- Parameters
match (re.Matchobject) – Match for substitution.
- Returns
Processed text.
- Return type
text (str)
-
sub_text(match)[source]¶ Helper method to be passed to re.sub, for handling all substitutions.
- Parameters
match (re.Matchobject) – Match for substitution.
- Returns
Processed text.
- Return type
text (str)
-
tabstop= 4¶
-
underline= '\x1b[4m'¶
-
unhilite= '\x1b[22m'¶
-
evennia.utils.utils module¶
General helper functions that don’t fit neatly under any given category.
They provide some useful string and conversion methods that might be of use when designing your own game.
-
class
evennia.utils.utils.LimitedSizeOrderedDict(*args, **kwargs)[source]¶ Bases:
collections.OrderedDictThis dictionary subclass is both ordered and limited to a maximum number of elements. Its main use is to hold a cache that can never grow out of bounds.
-
__init__(*args, **kwargs)[source]¶ Limited-size ordered dict.
- Kwargs:
- size_limit (int): Use this to limit the number of elements
alloweds to be in this list. By default the overshooting elements will be removed in FIFO order.
- fifo (bool, optional): Defaults to True. Remove overshooting elements
in FIFO order. If False, remove in FILO order.
-
-
evennia.utils.utils._DA()¶ Implement delattr(self, name).
-
evennia.utils.utils._GA()¶ Return getattr(self, name).
-
evennia.utils.utils._SA()¶ Implement setattr(self, name, value).
-
evennia.utils.utils.all_from_module(module)[source]¶ Return all global-level variables defined in a module.
- Parameters
module (str, module) – This can be either a Python path (dot-notation like evennia.objects.models), an absolute path (e.g. /home/eve/evennia/evennia/objects.models.py) or an already imported module object (e.g. models)
- Returns
- A dict of {variablename: variable} for all
variables in the given module.
- Return type
variables (dict)
Notes
Ignores modules and variable names starting with an underscore.
-
evennia.utils.utils.at_search_result(matches, caller, query='', quiet=False, **kwargs)[source]¶ This is a generic hook for handling all processing of a search result, including error reporting. This is also called by the cmdhandler to manage errors in command lookup.
- Parameters
matches (list) – This is a list of 0, 1 or more typeclass instances or Command instances, the matched result of the search. If 0, a nomatch error should be echoed, and if >1, multimatch errors should be given. Only if a single match should the result pass through.
caller (Object) – The object performing the search and/or which should
error messages. (receive) –
query (str, optional) – The search query used to produce matches.
quiet (bool, optional) – If True, no messages will be echoed to caller on errors.
- Kwargs:
nofound_string (str): Replacement string to echo on a notfound error. multimatch_string (str): Replacement string to echo on a multimatch error.
- Returns
- This is always a single result
or None. If None, any error reporting/handling should already have happened. The returned object is of the type we are checking multimatches for (e.g. Objects or Commands)
- Return type
processed_result (Object or None)
-
evennia.utils.utils.callables_from_module(module)[source]¶ Return all global-level callables defined in a module.
- Parameters
module (str, module) – A python-path to a module or an actual module object.
- Returns
A dict of {name: callable, …} from the module.
- Return type
callables (dict)
Notes
Will ignore callables whose names start with underscore “_”.
-
evennia.utils.utils.calledby(callerdepth=1)[source]¶ Only to be used for debug purposes. Insert this debug function in another function; it will print which function called it.
- Parameters
callerdepth (int) – Must be larger than 0. When > 1, it will print the caller of the caller etc.
- Returns
- A debug string detailing which routine called
us.
- Return type
calledby (str)
-
evennia.utils.utils.check_evennia_dependencies()[source]¶ Checks the versions of Evennia’s dependencies including making some checks for runtime libraries.
- Returns
- False if a show-stopping version mismatch is
found.
- Return type
result (bool)
-
evennia.utils.utils.class_from_module(path, defaultpaths=None)[source]¶ Return a class from a module, given the module’s path. This is primarily used to convert db_typeclass_path:s to classes.
- Parameters
path (str) – Full Python dot-path to module.
defaultpaths (iterable, optional) – If a direct import from path fails, try subsequent imports by prepending those paths to path.
- Returns
An uninstatiated class recovered from path.
- Return type
class (Class)
- Raises
ImportError – If all loading failed.
-
evennia.utils.utils.columnize(string, columns=2, spacing=4, align='l', width=None)[source]¶ Break a string into a number of columns, using as little vertical space as possible.
- Parameters
string (str) – The string to columnize.
columns (int, optional) – The number of columns to use.
spacing (int, optional) – How much space to have between columns.
width (int, optional) – The max width of the columns. Defaults to client’s default width.
- Returns
Text divided into columns.
- Return type
columns (str)
- Raises
RuntimeError – If given invalid values.
-
evennia.utils.utils.crop(text, width=None, suffix='[...]')[source]¶ Crop text to a certain width, throwing away text from too-long lines.
- Parameters
text (str) – Text to crop.
width (int, optional) – Width of line to crop, in characters.
suffix (str, optional) – This is appended to the end of cropped lines to show that the line actually continues. Cropping will be done so that the suffix will also fit within the given width. If width is too small to fit both crop and suffix, the suffix will be dropped.
- Returns
The cropped text.
- Return type
text (str)
-
evennia.utils.utils.datetime_format(dtobj)[source]¶ Pretty-prints the time since a given time.
- Parameters
dtobj (datetime) – An datetime object, e.g. from Django’s DateTimeField.
- Returns
- A string describing how long ago dtobj
took place.
- Return type
deltatime (str)
-
evennia.utils.utils.dbid_to_obj(inp, objclass, raise_errors=True)¶ Convert a #dbref to a valid object.
- Parameters
inp (str or int) – A valid #dbref.
objclass (class) – A valid django model to filter against.
raise_errors (bool, optional) – Whether to raise errors or return None on errors.
- Returns
An entity loaded from the dbref.
- Return type
obj (Object or None)
- Raises
Exception – If raise_errors is True and objclass.objects.get(id=dbref) did not return a valid object.
-
evennia.utils.utils.dbref(inp, reqhash=True)[source]¶ Converts/checks if input is a valid dbref.
- Parameters
inp (int, str) – A database ref on the form N or #N.
reqhash (bool, optional) – Require the #N form to accept input as a valid dbref.
- Returns
- The integer part of the dbref or None
if input was not a valid dbref.
- Return type
dbref (int or None)
-
evennia.utils.utils.dbref_to_obj(inp, objclass, raise_errors=True)[source]¶ Convert a #dbref to a valid object.
- Parameters
inp (str or int) – A valid #dbref.
objclass (class) – A valid django model to filter against.
raise_errors (bool, optional) – Whether to raise errors or return None on errors.
- Returns
An entity loaded from the dbref.
- Return type
obj (Object or None)
- Raises
Exception – If raise_errors is True and objclass.objects.get(id=dbref) did not return a valid object.
-
evennia.utils.utils.dedent(text, baseline_index=None)[source]¶ Safely clean all whitespace at the left of a paragraph.
- Parameters
text (str) – The text to dedent.
baseline_index (int or None, optional) – Which row to use as a ‘base’ for the indentation. Lines will be dedented to this level but no further. If None, indent so as to completely deindent the least indented text.
- Returns
Dedented string.
- Return type
text (str)
Notes
This is useful for preserving triple-quoted string indentation while still shifting it all to be next to the left edge of the display.
-
evennia.utils.utils.deepsize(obj, max_depth=4)[source]¶ Get not only size of the given object, but also the size of objects referenced by the object, down to max_depth distance from the object.
- Parameters
obj (object) – the object to be measured.
max_depth (int, optional) – maximum referential distance from obj that deepsize() should cover for measuring objects referenced by obj.
- Returns
deepsize of obj in Bytes.
- Return type
size (int)
Notes
This measure is necessarily approximate since some memory is shared between objects. The max_depth of 4 is roughly tested to give reasonable size information about database models and their handlers.
-
evennia.utils.utils.delay(timedelay, callback, *args, **kwargs)[source]¶ Delay the return of a value.
- Parameters
timedelay (int or float) – The delay in seconds
callback (callable) – Will be called as callback(*args, **kwargs) after timedelay seconds.
args (any, optional) – Will be used as arguments to callback
- Kwargs:
- persistent (bool, optional): should make the delay persistent
over a reboot or reload
any (any): Will be used as keyword arguments to callback.
- Returns
- Will fire with callback after
timedelay seconds. Note that if timedelay() is used in the commandhandler callback chain, the callback chain can be defined directly in the command body and don’t need to be specified here.
- Return type
deferred (deferred)
Note
The task handler (evennia.scripts.taskhandler.TASK_HANDLER) will be called for persistent or non-persistent tasks. If persistent is set to True, the callback, its arguments and other keyword arguments will be saved in the database, assuming they can be. The callback will be executed even after a server restart/reload, taking into account the specified delay (and server down time).
-
evennia.utils.utils.fill(text, width=None, indent=0)¶ Safely wrap text to a certain number of characters.
- Parameters
text (str) – The text to wrap.
width (int, optional) – The number of characters to wrap to.
indent (int) – How much to indent each line (with whitespace).
- Returns
Properly wrapped text.
- Return type
text (str)
-
evennia.utils.utils.format_grid(elements, width=78, sep=' ', verbatim_elements=None)[source]¶ This helper function makes a ‘grid’ output, where it distributes the given string-elements as evenly as possible to fill out the given width. will not work well if the variation of length is very big!
- Parameters
elements (iterable) – A 1D list of string elements to put in the grid.
width (int, optional) – The width of the grid area to fill.
sep (str, optional) – The extra separator to put between words. If set to the empty string, words may run into each other.
verbatim_elements (list, optional) – This is a list of indices pointing to specific items in the elements list. An element at this index will not be included in the calculation of the slot sizes. It will still be inserted into the grid at the correct position and may be surrounded by padding unless filling the entire line. This is useful for embedding decorations in the grid, such as horizontal bars.
- Returns
- The grid as a list of ready-formatted rows. We return it
like this to make it easier to insert decorations between rows, such as horizontal bars.
- Return type
gridstr (list)
-
evennia.utils.utils.format_table(table, extra_space=1)[source]¶ Note: evennia.utils.evtable is more powerful than this, but this function can be useful when the number of columns and rows are unknown and must be calculated on the fly.
- Args.
- table (list): A list of lists to represent columns in the
table: [[val,val,val,…], [val,val,val,…], …], where each val will be placed on a separate row in the column. All columns must have the same number of rows (some positions may be empty though).
- extra_space (int, optional): Sets how much minimum extra
padding (in characters) should be left between columns.
- Returns:
- table (list): A list of lists representing the rows to print
out one by one.
- Notes:
The function formats the columns to be as wide as the widest member of each column.
Examples:
-
evennia.utils.utils.fuzzy_import_from_module(path, variable, default=None, defaultpaths=None)[source]¶ Import a variable based on a fuzzy path. First the literal path will be tried, then all given defaultpaths will be prepended to see a match is found.
- Parameters
path (str) – Full or partial python path.
variable (str) – Name of variable to import from module.
default (string, optional) – Default value to use if a variable fails to be extracted. Ignored if variable is not given.
defaultpaths (iterable, options) – Python paths to attempt in order if importing directly from path doesn’t work.
- Returns
- The variable imported from the module, or default, if
not found.
- Return type
value (any)
-
evennia.utils.utils.get_all_typeclasses(parent=None)[source]¶ List available typeclasses from all available modules.
- Parameters
parent (str, optional) – If given, only return typeclasses inheriting (at any distance) from this parent.
- Returns
On the form {“typeclass.path”: typeclass, …}
- Return type
typeclasses (dict)
Notes
This will dynamicall retrieve all abstract django models inheriting at any distance from the TypedObject base (aka a Typeclass) so it will work fine with any custom classes being added.
-
evennia.utils.utils.get_evennia_pids()[source]¶ Get the currently valid PIDs (Process IDs) of the Portal and Server by trying to access a PID file.
- Returns
- The PIDs of the respective processes,
or two None values if not found.
- Return type
server, portal (tuple)
Examples
This can be used to determine if we are in a subprocess by something like:
`python self_pid = os.getpid() server_pid, portal_pid = get_evennia_pids() is_subprocess = self_pid not in (server_pid, portal_pid) `
-
evennia.utils.utils.get_evennia_version(mode='long')[source]¶ Helper method for getting the current evennia version.
- Parameters
mode (str, optional) – One of: - long: 0.9.0 rev342453534 - short: 0.9.0 - pretty: Evennia 0.9.0
- Returns
The version string.
- Return type
version (str)
-
evennia.utils.utils.get_game_dir_path()[source]¶ This is called by settings_default in order to determine the path of the game directory.
- Returns
Full OS path to the game dir
- Return type
path (str)
-
evennia.utils.utils.has_parent(basepath, obj)[source]¶ Checks if basepath is somewhere in `obj`s parent tree.
- Parameters
basepath (str) – Python dotpath to compare against obj path.
obj (any) – Object whose path is to be checked.
- Returns
If the check was successful or not.
- Return type
has_parent (bool)
-
evennia.utils.utils.host_os_is(osname)[source]¶ Check to see if the host OS matches the query.
- Parameters
osname (str) – Common names are “posix” (linux/unix/mac) and “nt” (windows).
is_os (bool) – If the os matches or not.
-
evennia.utils.utils.inherits_from(obj, parent)[source]¶ Takes an object and tries to determine if it inherits at any distance from parent.
- Parameters
obj (any) – Object to analyze. This may be either an instance or a class.
parent (any) – Can be either instance, class or python path to class.
- Returns
If parent is a parent to obj or not.
- Return type
inherits_from (bool)
Notes
What differs this function from e.g. isinstance() is that obj may be both an instance and a class, and parent may be an instance, a class, or the python path to a class (counting from the evennia root directory).
-
evennia.utils.utils.interactive(func)[source]¶ Decorator to make a method pausable with yield(seconds) and able to ask for user-input with response=yield(question). For the question-asking to work, ‘caller’ must the name of an argument or kwarg to the decorated function.
Note that this turns the method into a generator.
Example usage:
@interactive def myfunc(caller):
caller.msg(“This is a test”) # wait five seconds yield(5) # ask user (caller) a question response = yield(“Do you want to continue waiting?”) if response == “yes”:
yield(5)
- else:
# …
-
evennia.utils.utils.is_iter(obj)[source]¶ Checks if an object behaves iterably.
- Parameters
obj (any) – Entity to check for iterability.
- Returns
If obj is iterable or not.
- Return type
is_iterable (bool)
Notes
Strings are not accepted as iterable (although they are actually iterable), since string iterations are usually not what we want to do with a string.
-
evennia.utils.utils.justify(text, width=None, align='f', indent=0)[source]¶ Fully justify a text so that it fits inside width. When using full justification (default) this will be done by padding between words with extra whitespace where necessary. Paragraphs will be retained.
- Parameters
text (str) – Text to justify.
width (int, optional) – The length of each line, in characters.
align (str, optional) – The alignment, ‘l’, ‘c’, ‘r’ or ‘f’ for left, center, right or full justification respectively.
indent (int, optional) – Number of characters indentation of entire justified text block.
- Returns
The justified and indented block of text.
- Return type
justified (str)
-
evennia.utils.utils.latinify(string, default='?', pure_ascii=False)[source]¶ Convert a unicode string to “safe” ascii/latin-1 characters. This is used as a last resort when normal encoding does not work.
- Parameters
string (str) – A string to convert to ‘safe characters’ convertable to an latin-1 bytestring later.
default (str, optional) – Characters resisting mapping will be replaced with this character or string. The intent is to apply an encode operation on the string soon after.
- Returns
- A ‘latinified’ string where each unicode character has been
replaced with a ‘safe’ equivalent available in the ascii/latin-1 charset.
- Return type
string (str)
Notes
- This is inspired by the gist by Ricardo Murri:
-
class
evennia.utils.utils.lazy_property(func, name=None, doc=None)[source]¶ Bases:
objectDelays loading of property until first access. Credit goes to the Implementation in the werkzeug suite: http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property
This should be used as a decorator in a class and in Evennia is mainly used to lazy-load handlers:
Once initialized, the AttributeHandler will be available as a property “attributes” on the object.
-
evennia.utils.utils.list_to_string(inlist, endsep='and', addquote=False)[source]¶ This pretty-formats a list as string output, adding an optional alternative separator to the second to last entry. If addquote is True, the outgoing strings will be surrounded by quotes.
- Parameters
inlist (list) – The list to print.
endsep (str, optional) – If set, the last item separator will be replaced with this value.
addquote (bool, optional) – This will surround all outgoing values with double quotes.
- Returns
The list represented as a string.
- Return type
liststr (str)
Examples
-
evennia.utils.utils.m_len(target)[source]¶ Provides length checking for strings with MXP patterns, and falls back to normal len for other objects.
- Parameters
target (string) – A string with potential MXP components to search.
- Returns
The length of target, ignoring MXP components.
- Return type
length (int)
-
evennia.utils.utils.make_iter(obj)[source]¶ Makes sure that the object is always iterable.
- Parameters
obj (any) – Object to make iterable.
- Returns
- The same object
passed-through or made iterable.
- Return type
iterable (list or iterable)
-
evennia.utils.utils.mod_import(module)[source]¶ A generic Python module loader.
- Parameters
module (str, module) – This can be either a Python path (dot-notation like evennia.objects.models), an absolute path (e.g. /home/eve/evennia/evennia/objects/models.py) or an already imported module object (e.g. models)
- Returns
An imported module. If the input argument was already a module, this is returned as-is, otherwise the path is parsed and imported. Returns None and logs error if import failed.
- Return type
(module or None)
-
evennia.utils.utils.mod_import_from_path(path)[source]¶ Load a Python module at the specified path.
- Parameters
path (str) – An absolute path to a Python module to load.
- Returns
An imported module if the path was a valid Python module. Returns None if the import failed.
- Return type
(module or None)
-
evennia.utils.utils.object_from_module(path, defaultpaths=None)¶ Return a class from a module, given the module’s path. This is primarily used to convert db_typeclass_path:s to classes.
- Parameters
path (str) – Full Python dot-path to module.
defaultpaths (iterable, optional) – If a direct import from path fails, try subsequent imports by prepending those paths to path.
- Returns
An uninstatiated class recovered from path.
- Return type
class (Class)
- Raises
ImportError – If all loading failed.
-
evennia.utils.utils.pad(text, width=None, align='c', fillchar=' ')[source]¶ Pads to a given width.
- Parameters
text (str) – Text to pad.
width (int, optional) – The width to pad to, in characters.
align (str, optional) – This is one of ‘c’, ‘l’ or ‘r’ (center, left or right).
fillchar (str, optional) – The character to fill with.
- Returns
The padded text.
- Return type
text (str)
-
evennia.utils.utils.percent(value, minval, maxval, formatting='{:3.1f}%')[source]¶ Get a value in an interval as a percentage of its position in that interval. This also understands negative numbers.
- Parameters
value (number) – This should be a value minval<=value<=maxval.
minval (number or None) – Smallest value in interval. This could be None for an open interval (then return will always be 100%)
maxval (number or None) – Biggest value in interval. This could be None for an open interval (then return will always be 100%)
formatted (str, optional) – This is a string that should accept one formatting tag. This will receive the current value as a percentage. If None, the raw float will be returned instead.
- Returns
- The formatted value or the raw percentage
as a float.
- Return type
str or float
Notes
We try to handle a weird interval gracefully. - If either maxval or minval is None (open interval),
we (aribtrarily) assume 100%.
If minval > maxval, we return 0%.
- If minval == maxval == value we are looking at a single value match
and return 100%.
If minval == maxval != value we return 0%.
- If value not in [minval..maxval], we set value to the closest
boundary, so the result will be 0% or 100%, respectively.
-
evennia.utils.utils.percentile(iterable, percent, key=<function <lambda>>)[source]¶ Find the percentile of a list of values.
- Parameters
iterable (iterable) – A list of values. Note N MUST BE already sorted.
percent (float) – A value from 0.0 to 1.0.
key (callable, optional) –
@return - the percentile of the values
-
evennia.utils.utils.pypath_to_realpath(python_path, file_ending='.py', pypath_prefixes=None)[source]¶ Converts a dotted Python path to an absolute path under the Evennia library directory or under the current game directory.
- Parameters
python_path (str) – A dot-python path
file_ending (str) – A file ending, including the period.
pypath_prefixes (list) – A list of paths to test for existence. These should be on python.path form. EVENNIA_DIR and GAME_DIR are automatically checked, they need not be added to this list.
- Returns
- All existing, absolute paths created by
converting python_path to an absolute paths and/or prepending python_path by settings.EVENNIA_DIR, settings.GAME_DIR and by`pypath_prefixes` respectively.
- Return type
abspaths (list)
Notes
This will also try a few combinations of paths to allow cases where pypath is given including the “evennia.” or “mygame.” prefixes.
-
evennia.utils.utils.random_string_from_module(module)[source]¶ Returns a random global string from a module.
- Parameters
module (string or module) – Python path, absolute path or a module.
- Returns
A random stribg variable from module.
- Return type
random (string)
-
evennia.utils.utils.run_async(to_execute, *args, **kwargs)[source]¶ Runs a function or executes a code snippet asynchronously.
- Parameters
to_execute (callable) – If this is a callable, it will be executed with *args and non-reserved *kwargs as arguments. The callable will be executed using ProcPool, or in a thread if ProcPool is not available.
- Kwargs:
- at_return (callable): Should point to a callable with one
argument. It will be called with the return value from to_execute.
- at_return_kwargs (dict): This dictionary will be used as
keyword arguments to the at_return callback.
- at_err (callable): This will be called with a Failure instance
if there is an error in to_execute.
- at_err_kwargs (dict): This dictionary will be used as keyword
arguments to the at_err errback.
Notes
All other *args and **kwargs will be passed on to to_execute. Run_async will relay executed code to a thread or procpool.
Use this function with restrain and only for features/commands that you know has no influence on the cause-and-effect order of your game (commands given after the async function might be executed before it has finished). Accessing the same property from different threads can lead to unpredicted behaviour if you are not careful (this is called a “race condition”).
Also note that some databases, notably sqlite3, don’t support access from multiple threads simultaneously, so if you do heavy database access from your to_execute under sqlite3 you will probably run very slow or even get tracebacks.
-
evennia.utils.utils.server_services()[source]¶ Lists all services active on the Server. Observe that since services are launched in memory, this function will only return any results if called from inside the game.
- Returns
A dict of available services.
- Return type
services (dict)
-
evennia.utils.utils.string_from_module(module, variable=None, default=None)[source]¶ This is a wrapper for variable_from_module that requires return value to be a string to pass. It’s primarily used by login screen.
- Parameters
module (string or module) – Python path, absolute path or a module.
variable (string or iterable, optional) – Single variable name or iterable of variable names to extract. If not given, all variables in the module will be returned.
default (string, optional) – Default value to use if a variable fails to be extracted. Ignored if variable is not given.
- Returns
A single (string) value or a list of values depending on if variable is given or not. Errors in lists (such as the value not being a string) are replaced by the default argument.
- Return type
variables (value or list)
-
evennia.utils.utils.string_partial_matching(alternatives, inp, ret_index=True)[source]¶ Partially matches a string based on a list of alternatives. Matching is made from the start of each subword in each alternative. Case is not important. So e.g. “bi sh sw” or just “big” or “shiny” or “sw” will match “Big shiny sword”. Scoring is done to allow to separate by most common demoninator. You will get multiple matches returned if appropriate.
- Parameters
alternatives (list of str) – A list of possible strings to match.
inp (str) – Search criterion.
ret_index (bool, optional) – Return list of indices (from alternatives array) instead of strings.
- Returns
String-matches or indices if ret_index is True.
- Return type
matches (list)
-
evennia.utils.utils.string_similarity(string1, string2)[source]¶ - This implements a “cosine-similarity” algorithm as described for example in
Proceedings of the 22nd International Conference on Computation Linguistics (Coling 2008), pages 593-600, Manchester, August 2008.
The measure-vectors used is simply a “bag of words” type histogram (but for letters).
- Parameters
string1 (str) – String to compare (may contain any number of words).
string2 (str) – Second string to compare (any number of words).
- Returns
- A value 0…1 rating how similar the two
strings are.
- Return type
similarity (float)
-
evennia.utils.utils.string_suggestions(string, vocabulary, cutoff=0.6, maxnum=3)[source]¶ Given a string and a vocabulary, return a match or a list of suggestions based on string similarity.
- Parameters
string (str) – A string to search for.
vocabulary (iterable) – A list of available strings.
cutoff (int, 0-1) – Limit the similarity matches (the higher the value, the more exact a match is required).
maxnum (int) – Maximum number of suggestions to return.
- Returns
- Suggestions from vocabulary with a
similarity-rating that higher than or equal to cutoff. Could be empty if there are no matches.
- Return type
suggestions (list)
-
evennia.utils.utils.strip_control_sequences(string)[source]¶ Remove non-print text sequences.
- Parameters
string (str) – Text to strip.
- Returns.
text (str): Stripped text.
-
evennia.utils.utils.time_format(seconds, style=0)[source]¶ Function to return a ‘prettified’ version of a value in seconds.
- Parameters
seconds (int) – Number if seconds to format.
style (int) – One of the following styles: 0. “1d 08:30” 1. “1d” 2. “1 day, 8 hours, 30 minutes” 3. “1 day, 8 hours, 30 minutes, 10 seconds” 4. highest unit (like “3 years” or “8 months” or “1 second”)
- Returns
A pretty time string.
- Return type
timeformatted (str)
-
evennia.utils.utils.to_bytes(text, session=None)[source]¶ Try to encode the given text to bytes, using encodings from settings or from Session. Will always return a bytes, even if given something that is not str or bytes.
- Parameters
text (any) – The text to encode to bytes. If bytes, return unchanged. If not a str, convert to str before converting.
session (Session, optional) – A Session to get encoding info from. Will try this before falling back to settings.ENCODINGS.
- Returns
- the encoded text following the session’s protocol flag followed by the
encodings specified in settings.ENCODINGS. If all attempt fail, log the error and send the text with “?” in place of problematic characters. If the specified encoding cannot be found, the protocol flag is reset to utf-8. In any case, returns bytes.
- Return type
encoded_text (bytes)
Note
If text is already bytes, return it as is.
-
evennia.utils.utils.to_str(text, session=None)[source]¶ Try to decode a bytestream to a python str, using encoding schemas from settings or from Session. Will always return a str(), also if not given a str/bytes.
- Parameters
text (any) – The text to encode to bytes. If a str, return it. If also not bytes, convert to str using str() or repr() as a fallback.
session (Session, optional) – A Session to get encoding info from. Will try this before falling back to settings.ENCODINGS.
- Returns
The decoded text.
- Return type
decoded_text (str)
Note
If text is already str, return it as is.
-
evennia.utils.utils.uses_database(name='sqlite3')[source]¶ Checks if the game is currently using a given database. This is a shortcut to having to use the full backend name.
- Parameters
name (str) – One of ‘sqlite3’, ‘mysql’, ‘postgresql’
'oracle'. (or) –
- Returns
If the given database is used or not.
- Return type
uses (bool)
-
evennia.utils.utils.validate_email_address(emailaddress)[source]¶ Checks if an email address is syntactically correct.
- Parameters
emailaddress (str) – Email address to validate.
- Returns
If this is a valid email or not.
- Return type
is_valid (bool)
- Notes.
(This snippet was adapted from http://commandline.org.uk/python/email-syntax-check.)
-
evennia.utils.utils.variable_from_module(module, variable=None, default=None)[source]¶ Retrieve a variable or list of variables from a module. The variable(s) must be defined globally in the module. If no variable is given (or a list entry is None), all global variables are extracted from the module.
- Parameters
module (string or module) – Python path, absolute path or a module.
variable (string or iterable, optional) – Single variable name or iterable of variable names to extract. If not given, all variables in the module will be returned.
default (string, optional) – Default value to use if a variable fails to be extracted. Ignored if variable is not given.
- Returns
A single value or a list of values depending on if variable is given or not. Errors in lists are replaced by the default argument.
- Return type
variables (value or list)
-
evennia.utils.utils.wildcard_to_regexp(instring)[source]¶ Converts a player-supplied string that may have wildcards in it to regular expressions. This is useful for name matching.
- Parameters
instring (string) – A string that may potentially contain wildcards (* or ?).
- Returns
- A string where wildcards were replaced with
regular expressions.
- Return type
regex (str)
-
evennia.utils.utils.wrap(text, width=None, indent=0)[source]¶ Safely wrap text to a certain number of characters.
- Parameters
text (str) – The text to wrap.
width (int, optional) – The number of characters to wrap to.
indent (int) – How much to indent each line (with whitespace).
- Returns
Properly wrapped text.
- Return type
text (str)
evennia.utils.validatorfuncs module¶
Contains all the validation functions.
All validation functions must have a checker (probably a session) and entry arg.
They can employ more paramters at your leisure.
-
evennia.utils.validatorfuncs.boolean(entry, option_key='True/False', **kwargs)[source]¶ Simplest check in computer logic, right? This will take user input to flick the switch on or off :param entry: A value such as True, On, Enabled, Disabled, False, 0, or 1. :type entry: str :param option_key: What kind of Boolean we are setting. What Option is this for? :type option_key: str
- Returns
Boolean
-
evennia.utils.validatorfuncs.color(entry, option_key='Color', **kwargs)[source]¶ The color should be just a color character, so ‘r’ if red color is desired.
-
evennia.utils.validatorfuncs.datetime(entry, option_key='Datetime', account=None, from_tz=None, **kwargs)[source]¶ Process a datetime string in standard forms while accounting for the inputer’s timezone. Always returns a result in UTC.
- Parameters
entry (str) – A date string from a user.
option_key (str) – Name to display this datetime as.
account (AccountDB) – The Account performing this lookup. Unless from_tz is provided, the account’s timezone option will be used.
from_tz (pytz.timezone) – An instance of a pytz timezone object from the user. If not provided, tries to use the timezone option of the `account’. If neither one is provided, defaults to UTC.
- Returns
datetime in UTC.
- Raises
ValueError – If encountering a malformed timezone, date string or other format error.
-
evennia.utils.validatorfuncs.duration(entry, option_key='Duration', **kwargs)[source]¶ Take a string and derive a datetime timedelta from it.
- Parameters
entry (string) – This is a string from user-input. The intended format is, for example: “5d 2w 90s” for ‘five days, two weeks, and ninety seconds.’ Invalid sections are ignored.
option_key (str) – Name to display this query as.
- Returns
timedelta
-
evennia.utils.validatorfuncs.future(entry, option_key='Future Datetime', from_tz=None, **kwargs)[source]¶
-
evennia.utils.validatorfuncs.lock(entry, option_key='locks', access_options=None, **kwargs)[source]¶
-
evennia.utils.validatorfuncs.positive_integer(entry, option_key='Positive Integer', **kwargs)[source]¶