evennia.utils.utils

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.

evennia.utils.utils.is_iter(obj)[源代码]

Checks if an object behaves iterably.

参数

obj (any) – Entity to check for iterability.

返回

is_iterable (bool) – If obj is iterable or not.

提示

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.make_iter(obj)[源代码]

Makes sure that the object is always iterable.

参数

obj (any) – Object to make iterable.

返回

iterable (list or iterable)

The same object

passed-through or made iterable.

evennia.utils.utils.wrap(text, width=None, indent=0)[源代码]

Safely wrap text to a certain number of characters.

参数
  • 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).

返回

text (str) – Properly wrapped text.

evennia.utils.utils.fill(text, width=None, indent=0)

Safely wrap text to a certain number of characters.

参数
  • 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).

返回

text (str) – Properly wrapped text.

evennia.utils.utils.pad(text, width=None, align='c', fillchar=' ')[源代码]

Pads to a given width.

参数
  • 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.

返回

text (str) – The padded text.

evennia.utils.utils.crop(text, width=None, suffix='[...]')[源代码]

Crop text to a certain width, throwing away text from too-long lines.

参数
  • 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.

返回

text (str) – The cropped text.

evennia.utils.utils.dedent(text, baseline_index=None, indent=None)[源代码]

Safely clean all whitespace at the left of a paragraph.

参数
  • text (str) – The text to dedent.

  • baseline_index (int, 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.

  • indent (int, optional) – If given, force all lines to this indent. This bypasses baseline_index.

返回

text (str) – Dedented string.

提示

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.justify(text, width=None, align='l', indent=0, fillchar=' ')[源代码]

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.

参数
  • text (str) – Text to justify.

  • width (int, optional) – The length of each line, in characters.

  • align (str, optional) – The alignment, ‘l’, ‘c’, ‘r’, ‘f’ or ‘a’ for left, center, right, full justification. The ‘a’ stands for ‘absolute’ and means the text will be returned unmodified.

  • indent (int, optional) – Number of characters indentation of entire justified text block.

  • fillchar (str) – The character to use to fill. Defaults to empty space.

返回

justified (str) – The justified and indented block of text.

evennia.utils.utils.columnize(string, columns=2, spacing=4, align='l', width=None)[源代码]

Break a string into a number of columns, using as little vertical space as possible.

参数
  • 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.

返回

columns (str) – Text divided into columns.

引发

RuntimeError – If given invalid values.

evennia.utils.utils.iter_to_str(iterable, sep=',', endsep=', and', addquote=False)[源代码]

This pretty-formats an iterable 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.

参数
  • iterable (any) – Usually an iterable to print. Each element must be possible to present with a string. Note that if this is a generator, it will be consumed by this operation.

  • sep (str, optional) – The string to use as a separator for each item in the iterable.

  • endsep (str, optional) – The last item separator will be replaced with this value.

  • addquote (bool, optional) – This will surround all outgoing values with double quotes.

返回

str – The list represented as a string.

提示

Default is to use ‘Oxford comma’, like 1, 2, 3, and 4.

实际案例

>>> iter_to_string([1,2,3], endsep=',')
'1, 2, 3'
>>> iter_to_string([1,2,3], endsep='')
'1, 2 3'
>>> iter_to_string([1,2,3], ensdep='and')
'1, 2 and 3'
>>> iter_to_string([1,2,3], sep=';', endsep=';')
'1; 2; 3'
>>> iter_to_string([1,2,3], addquote=True)
'"1", "2", and "3"'
evennia.utils.utils.list_to_string(iterable, sep=',', endsep=', and', addquote=False)

This pretty-formats an iterable 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.

参数
  • iterable (any) – Usually an iterable to print. Each element must be possible to present with a string. Note that if this is a generator, it will be consumed by this operation.

  • sep (str, optional) – The string to use as a separator for each item in the iterable.

  • endsep (str, optional) – The last item separator will be replaced with this value.

  • addquote (bool, optional) – This will surround all outgoing values with double quotes.

返回

str – The list represented as a string.

提示

Default is to use ‘Oxford comma’, like 1, 2, 3, and 4.

实际案例

>>> iter_to_string([1,2,3], endsep=',')
'1, 2, 3'
>>> iter_to_string([1,2,3], endsep='')
'1, 2 3'
>>> iter_to_string([1,2,3], ensdep='and')
'1, 2 and 3'
>>> iter_to_string([1,2,3], sep=';', endsep=';')
'1; 2; 3'
>>> iter_to_string([1,2,3], addquote=True)
'"1", "2", and "3"'
evennia.utils.utils.iter_to_string(iterable, sep=',', endsep=', and', addquote=False)

This pretty-formats an iterable 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.

参数
  • iterable (any) – Usually an iterable to print. Each element must be possible to present with a string. Note that if this is a generator, it will be consumed by this operation.

  • sep (str, optional) – The string to use as a separator for each item in the iterable.

  • endsep (str, optional) – The last item separator will be replaced with this value.

  • addquote (bool, optional) – This will surround all outgoing values with double quotes.

返回

str – The list represented as a string.

提示

Default is to use ‘Oxford comma’, like 1, 2, 3, and 4.

实际案例

>>> iter_to_string([1,2,3], endsep=',')
'1, 2, 3'
>>> iter_to_string([1,2,3], endsep='')
'1, 2 3'
>>> iter_to_string([1,2,3], ensdep='and')
'1, 2 and 3'
>>> iter_to_string([1,2,3], sep=';', endsep=';')
'1; 2; 3'
>>> iter_to_string([1,2,3], addquote=True)
'"1", "2", and "3"'
evennia.utils.utils.compress_whitespace(text, max_linebreaks=1, max_spacing=2)[源代码]

Removes extra sequential whitespace in a block of text. This will also remove any trailing whitespace at the end.

参数

text (str) – A string which may contain excess internal whitespace.

关键字参数
  • max_linebreaks (int) – How many linebreak characters are allowed to occur in a row.

  • max_spacing (int) – How many spaces are allowed to occur in a row.

evennia.utils.utils.wildcard_to_regexp(instring)[源代码]

Converts a player-supplied string that may have wildcards in it to regular expressions. This is useful for name matching.

参数

instring (string) – A string that may potentially contain wildcards (* or ?).

返回

regex (str)

A string where wildcards were replaced with

regular expressions.

evennia.utils.utils.time_format(seconds, style=0)[源代码]

Function to return a ‘prettified’ version of a value in seconds.

参数
  • 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”)

返回

timeformatted (str) – A pretty time string.

evennia.utils.utils.datetime_format(dtobj)[源代码]

Pretty-prints the time since a given time.

参数

dtobj (datetime) – An datetime object, e.g. from Django’s DateTimeField.

返回

deltatime (str)

A string describing how long ago dtobj

took place.

evennia.utils.utils.host_os_is(osname)[源代码]

Check to see if the host OS matches the query.

参数
  • osname (str) – Common names are “posix” (linux/unix/mac) and “nt” (windows).

  • is_os (bool) – If the os matches or not.

evennia.utils.utils.get_evennia_version(mode='long')[源代码]

Helper method for getting the current evennia version.

参数

mode (str, optional) – One of: - long: 0.9.0 rev342453534 - short: 0.9.0 - pretty: Evennia 0.9.0

返回

version (str) – The version string.

evennia.utils.utils.pypath_to_realpath(python_path, file_ending='.py', pypath_prefixes=None)[源代码]

Converts a dotted Python path to an absolute path under the Evennia library directory or under the current game directory.

参数
  • 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.

返回

abspaths (list)

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.

提示

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.dbref(inp, reqhash=True)[源代码]

Converts/checks if input is a valid dbref.

参数
  • 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.

返回

dbref (int or None)

The integer part of the dbref or None

if input was not a valid dbref.

evennia.utils.utils.dbref_to_obj(inp, objclass, raise_errors=True)[源代码]

Convert a #dbref to a valid object.

参数
  • 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.

返回

obj (Object or None) – An entity loaded from the dbref.

引发

Exception – If raise_errors is True and objclass.objects.get(id=dbref) did not return a valid object.

evennia.utils.utils.dbid_to_obj(inp, objclass, raise_errors=True)

Convert a #dbref to a valid object.

参数
  • 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.

返回

obj (Object or None) – An entity loaded from the dbref.

引发

Exception – If raise_errors is True and objclass.objects.get(id=dbref) did not return a valid object.

evennia.utils.utils.latinify(string, default='?', pure_ascii=False)[源代码]

Convert a unicode string to “safe” ascii/latin-1 characters. This is used as a last resort when normal encoding does not work.

参数
  • string (str) – A string to convert to ‘safe characters’ convertible 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.

返回

string (str)

A ‘latinified’ string where each unicode character has been

replaced with a ‘safe’ equivalent available in the ascii/latin-1 charset.

提示

This is inspired by the gist by Ricardo Murri:

https://gist.github.com/riccardomurri/3c3ccec30f037be174d3

evennia.utils.utils.to_bytes(text, session=None)[源代码]

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.

参数
  • 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.

返回

encoded_text (bytes)

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.

提示

If text is already bytes, return it as is.

evennia.utils.utils.to_str(text, session=None)[源代码]

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.

参数
  • 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.

返回

decoded_text (str) – The decoded text.

提示

If text is already str, return it as is.

evennia.utils.utils.validate_email_address(emailaddress)[源代码]

Checks if an email address is syntactically correct. Makes use of the django email-validator for consistency.

参数

emailaddress (str) – Email address to validate.

返回

bool – If this is a valid email or not.

evennia.utils.utils.inherits_from(obj, parent)[源代码]

Takes an object and tries to determine if it inherits at any distance from parent.

参数
  • obj (any) – Object to analyze. This may be either an instance or a class.

  • parent (any) – Can be either an instance, a class or the python path to the class.

返回

inherits_from (bool) – If parent is a parent to obj or not.

提示

What differentiates this function from Python’s isinstance() is the flexibility in the types allowed for the object and parent being compared.

evennia.utils.utils.server_services()[源代码]

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.

返回

services (dict) – A dict of available services.

evennia.utils.utils.uses_database(name='sqlite3')[源代码]

Checks if the game is currently using a given database. This is a shortcut to having to use the full backend name.

参数

name (str) – One of ‘sqlite3’, ‘mysql’, ‘postgresql’ or ‘oracle’.

返回

uses (bool) – If the given database is used or not.

evennia.utils.utils.delay(timedelay, callback, *args, **kwargs)[源代码]

Delay the calling of a callback (function).

参数
  • timedelay (int or float) – The delay in seconds.

  • callback (callable) – Will be called as callback(*args, **kwargs) after timedelay seconds.

  • *args – Will be used as arguments to callback

关键字参数
  • persistent (bool, optional) – If True the delay remains after a server restart. persistent is False by default.

  • any (any) – Will be used as keyword arguments to callback.

返回

task (TaskHandlerTask)

An instance of a task.

Refer to, evennia.scripts.taskhandler.TaskHandlerTask

提示

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 (serialized) 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). Keep in mind that persistent tasks arguments and callback should not use memory references. If persistent is set to True the delay function will return an int which is the task’s id intended for use with TASK_HANDLER’s do_task and remove methods. All persistent tasks whose time delays have passed will be called on server startup.

evennia.utils.utils.repeat(interval, callback, persistent=True, idstring='', stop=False, store_key=None, *args, **kwargs)[源代码]

Start a repeating task using the TickerHandler.

参数
  • interval (int) – How often to call callback.

  • callback (callable) – This will be called with *args, **kwargs every interval seconds. This must be possible to pickle regardless of if persistent is set or not!

  • persistent (bool, optional) – If ticker survives a server reload.

  • idstring (str, optional) – Separates multiple tickers. This is useful mainly if wanting to set up multiple repeats for the same interval/callback but with different args/kwargs.

  • stop (bool, optional) – If set, use the given parameters to _stop_ a running ticker instead of creating a new one.

  • store_key (tuple, optional) – This is only used in combination with stop and should be the return given from the original repeat call. If this is given, all other args except stop are ignored.

  • *args – Used as arguments to callback.

  • **kwargs – Keyword-arguments to pass to callback.

返回

tuple or None – The tuple is the store_key - the identifier for the created ticker. Store this and pass into unrepat() in order to to stop this ticker later. Returns None if stop=True.

引发

KeyError – If trying to stop a ticker that was not found.

evennia.utils.utils.unrepeat(store_key)[源代码]

This is used to stop a ticker previously started with repeat.

参数

store_key (tuple) – This is the return from repeat, used to uniquely identify the ticker to stop. Without the store_key, the ticker must be stopped by passing its parameters to TICKER_HANDLER.remove directly.

返回

bool

True if a ticker was stopped, False if not (for example because no

matching ticker was found or it was already stopped).

evennia.utils.utils.run_async(to_execute, *args, **kwargs)[源代码]

Runs a function or executes a code snippet asynchronously.

参数

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.

关键字参数
  • 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.

提示

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.check_evennia_dependencies()[源代码]

Checks the versions of Evennia’s dependencies including making some checks for runtime libraries.

返回

result (bool)

False if a show-stopping version mismatch is

found.

evennia.utils.utils.has_parent(basepath, obj)[源代码]

Checks if basepath is somewhere in obj’s parent tree.

参数
  • basepath (str) – Python dotpath to compare against obj path.

  • obj (any) – Object whose path is to be checked.

返回

has_parent (bool) – If the check was successful or not.

evennia.utils.utils.mod_import_from_path(path)[源代码]

Load a Python module at the specified path.

参数

path (str) – An absolute path to a Python module to load.

返回

(module or None) – An imported module if the path was a valid Python module. Returns None if the import failed.

evennia.utils.utils.mod_import(module)[源代码]

A generic Python module loader.

参数

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)

返回

(module or None) – 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.

evennia.utils.utils.all_from_module(module)[源代码]

Return all global-level variables defined in a module.

参数

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)

返回

dict

A dict of {variablename: variable} for all

variables in the given module.

提示

Ignores modules and variable names starting with an underscore, as well as variables imported into the module from other modules.

evennia.utils.utils.callables_from_module(module)[源代码]

Return all global-level callables defined in a module.

参数

module (str, module) – A python-path to a module or an actual module object.

返回

callables (dict) – A dict of {name: callable, …} from the module.

提示

Will ignore callables whose names start with underscore “_”.

evennia.utils.utils.variable_from_module(module, variable=None, default=None)[源代码]

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.

参数
  • 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.

返回

variables (value or list) – 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.

evennia.utils.utils.string_from_module(module, variable=None, default=None)[源代码]

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.

参数
  • 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.

返回

variables (value or list) – 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.

evennia.utils.utils.random_string_from_module(module)[源代码]

Returns a random global string from a module.

参数

module (string or module) – Python path, absolute path or a module.

返回

random (string) – A random stribg variable from module.

evennia.utils.utils.fuzzy_import_from_module(path, variable, default=None, defaultpaths=None)[源代码]

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.

参数
  • 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.

返回

value (any)

The variable imported from the module, or default, if

not found.

evennia.utils.utils.class_from_module(path, defaultpaths=None, fallback=None)[源代码]

Return a class from a module, given the class’ full python path. This is primarily used to convert db_typeclass_path:s to classes.

参数
  • 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.

  • fallback (str) – If all other attempts fail, use this path as a fallback. This is intended as a last-resort. In the example of Evennia loading, this would be a path to a default parent class in the evennia repo itself.

返回

class (Class) – An uninstantiated class recovered from path.

引发

ImportError – If all loading failed.

evennia.utils.utils.object_from_module(path, defaultpaths=None, fallback=None)

Return a class from a module, given the class’ full python path. This is primarily used to convert db_typeclass_path:s to classes.

参数
  • 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.

  • fallback (str) – If all other attempts fail, use this path as a fallback. This is intended as a last-resort. In the example of Evennia loading, this would be a path to a default parent class in the evennia repo itself.

返回

class (Class) – An uninstantiated class recovered from path.

引发

ImportError – If all loading failed.

evennia.utils.utils.init_new_account(account)[源代码]

Deprecated.

evennia.utils.utils.string_similarity(string1, string2)[源代码]

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).

参数
  • string1 (str) – String to compare (may contain any number of words).

  • string2 (str) – Second string to compare (any number of words).

返回

similarity (float)

A value 0…1 rating how similar the two

strings are.

evennia.utils.utils.string_suggestions(string, vocabulary, cutoff=0.6, maxnum=3)[源代码]

Given a string and a vocabulary, return a match or a list of suggestions based on string similarity.

参数
  • 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.

返回

suggestions (list) – Suggestions from vocabulary with a similarity-rating that higher than or equal to cutoff. Could be empty if there are no matches.

evennia.utils.utils.string_partial_matching(alternatives, inp, ret_index=True)[源代码]

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 denominator. You will get multiple matches returned if appropriate.

参数
  • 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.

返回

matches (list) – String-matches or indices if ret_index is True.

evennia.utils.utils.group_objects_by_key_and_desc(objects, caller=None, **kwargs)[源代码]

Groups a list of objects by their key and description. This is used to group visibly identical objects together, for example for inventory listings.

参数
  • objects (list) – A list of objects to group. These must be DefaultObject.

  • caller (Object, optional) – The object looking at the objects, used to get the description and key of each object.

  • **kwargs – Passed into each object’s get_display_name/desc methods.

返回

iterable

An iterable of tuples, where each tuple is on the form

(numbered_name, description, [objects]).

evennia.utils.utils.format_table(table, extra_space=1)[源代码]

Format a 2D array of strings into a multi-column table.

参数
  • 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.

返回

list – A list of lists representing the rows to print out one by one.

提示

The function formats the columns to be as wide as the widest member of each column.

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.

Examples:

ftable = format_table([[1,2,3], [4,5,6]])
string = ""
for ir, row in enumerate(ftable):
    if ir == 0:
        # make first row white
        string += "\n|w" + "".join(row) + "|n"
    else:
        string += "\n" + "".join(row)
print(string)
evennia.utils.utils.percent(value, minval, maxval, formatting='{:3.1f}%')[源代码]

Get a value in an interval as a percentage of its position in that interval. This also understands negative numbers.

参数
  • 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.

返回

str or float – The formatted value or the raw percentage as a float.

提示

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>>)[源代码]

Find the percentile of a list of values.

参数
  • 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) –

返回

float – The percentile of the values

evennia.utils.utils.format_grid(elements, width=78, sep=' ', verbatim_elements=None, line_prefix='')[源代码]

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!

参数
  • 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.

  • ignore_ansi (bool, optional) – Ignore ansi markups when calculating white spacing.

  • line_prefix (str, optional) – A prefix to add at the beginning of each line. This can e.g. be used to preserve line color across line breaks.

返回

list – 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.

evennia.utils.utils.get_evennia_pids()[源代码]

Get the currently valid PIDs (Process IDs) of the Portal and Server by trying to access a PID file.

返回

server, portal (tuple)

The PIDs of the respective processes,

or two None values if not found.

实际案例

This can be used to determine if we are in a subprocess by

self_pid = os.getpid()
server_pid, portal_pid = get_evennia_pids()
is_subprocess = self_pid not in (server_pid, portal_pid)
evennia.utils.utils.deepsize(obj, max_depth=4)[源代码]

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.

参数
  • 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.

返回

size (int) – deepsize of obj in Bytes.

提示

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.

class evennia.utils.utils.lazy_property(func: collections.abc.Callable[, TProp], name=None, doc=None)[源代码]

基类:typing.Generic

Delays 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:

@lazy_property
def attributes(self):
    return AttributeHandler(self)

Once initialized, the AttributeHandler will be available as a property “attributes” on the object. This is read-only since this functionality is pretty much exclusively used by handlers.

__init__(func: collections.abc.Callable[, TProp], name=None, doc=None)[源代码]

Store all properties for now

evennia.utils.utils.strip_control_sequences(string)[源代码]

Remove non-print text sequences.

参数

string (str) – Text to strip.

Returns.

text (str): Stripped text.

evennia.utils.utils.calledby(callerdepth=1)[源代码]

Only to be used for debug purposes. Insert this debug function in another function; it will print which function called it.

参数

callerdepth (int or None) – If None, show entire stack. If int, must be larger than 0. When > 1, it will print the sequence to that depth.

返回

calledby (str) – A debug string detailing the code that called us.

evennia.utils.utils.m_len(target)[源代码]

Provides length checking for strings with MXP patterns, and falls back to normal len for other objects.

参数

target (str) – A string with potential MXP components to search.

返回

length (int) – The length of target, ignoring MXP components.

evennia.utils.utils.display_len(target)[源代码]

Calculate the ‘visible width’ of text. This is not necessarily the same as the number of characters in the case of certain asian characters. This will also strip MXP patterns.

参数

target (any) – Something to measure the length of. If a string, it will be measured keeping asian-character and MXP links in mind.

返回

int – The visible width of the target.

evennia.utils.utils.at_search_result(matches, caller, query='', quiet=False, **kwargs)[源代码]

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.

参数
  • 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.

关键字参数
  • nofound_string (str) – Replacement string to echo on a notfound error.

  • multimatch_string (str) – Replacement string to echo on a multimatch error.

返回

processed_result (Object or None) – 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)

class evennia.utils.utils.LimitedSizeOrderedDict(*args, **kwargs)[源代码]

基类:collections.OrderedDict

This 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)[源代码]

Limited-size ordered dict.

关键字参数
  • 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.

update([E, ]**F) → None. Update D from dict/iterable E and F.[源代码]

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

evennia.utils.utils.get_game_dir_path()[源代码]

This is called by settings_default in order to determine the path of the game directory.

返回

path (str) – Full OS path to the game dir

evennia.utils.utils.get_all_typeclasses(parent=None)[源代码]

List available typeclasses from all available modules.

参数

parent (str, optional) – If given, only return typeclasses inheriting (at any distance) from this parent.

返回

dict – On the form {“typeclass.path”: typeclass, …}

提示

This will dynamically 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_all_cmdsets(parent=None)[源代码]

List available cmdsets from all available modules.

参数

parent (str, optional) – If given, only return cmdsets inheriting (at any distance) from this parent.

返回

dict – On the form {“cmdset.path”: cmdset, …}

提示

This will dynamically retrieve all abstract django models inheriting at any distance from the CmdSet base so it will work fine with any custom classes being added.

evennia.utils.utils.interactive(func)[源代码]

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, one of the args or kwargs to the decorated function must be named ‘caller’.

引发
  • ValueError – If asking an interactive question but the decorated function has no arg or kwarg named ‘caller’.

  • ValueError – If passing non int/float to yield using for pausing.

实际案例

@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:
        # ...

提示

This turns the decorated function or method into a generator.

evennia.utils.utils.safe_convert_to_types(converters, *args, raise_errors=True, **kwargs)[源代码]

Helper function to safely convert inputs to expected data types.

参数
  • converters (tuple) – A tuple ((converter, converter,…), {kwarg: converter, …}) to match a converter to each element in *args and **kwargs. Each converter will will be called with the arg/kwarg-value as the only argument. If there are too few converters given, the others will simply not be converter. If the converter is given as the string ‘py’, it attempts to run safe_eval/literal_eval on the input arg or kwarg value. It’s possible to skip the arg/kwarg part of the tuple, an empty tuple/dict will then be assumed.

  • *args – The arguments to convert with argtypes.

  • raise_errors (bool, optional) – If set, raise any errors. This will abort the conversion at that arg/kwarg. Otherwise, just skip the conversion of the failing arg/kwarg. This will be set by the FuncParser if this is used as a part of a FuncParser callable.

  • **kwargs – The kwargs to convert with kwargtypes

返回

tuple(args, kwargs) in converted form.

引发
  • utils.funcparser.ParsingError – If parsing failed in the ‘py’ converter. This also makes this compatible with the FuncParser interface.

  • any – Any other exception raised from other converters, if raise_errors is True.

提示

This function is often used to validate/convert input from untrusted sources. For security, the “py”-converter is deliberately limited and uses safe_eval/literal_eval which only supports simple expressions or simple containers with literals. NEVER use the python eval or exec methods as a converter for any untrusted input! Allowing untrusted sources to execute arbitrary python on your server is a severe security risk,

Example:

$funcname(1, 2, 3.0, c=[1,2,3])

def _funcname(*args, **kwargs):
    args, kwargs = safe_convert_input(((int, int, float), {'c': 'py'}), *args, **kwargs)
    # ...
evennia.utils.utils.strip_unsafe_input(txt, session=None, bypass_perms=None)[源代码]

Remove ‘unsafe’ text codes from text; these are used to elimitate exploits in user-provided data, such as html-tags, line breaks etc.

参数
  • txt (str) – The text to clean.

  • session (Session, optional) – A Session in order to determine if the check should be bypassed by permission (will be checked with the ‘perm’ lock, taking permission hierarchies into account).

  • bypass_perms (list, optional) – Iterable of permission strings to check for bypassing the strip. If not given, use settings.INPUT_CLEANUP_BYPASS_PERMISSIONS.

返回

str – The cleaned string.

提示

The INPUT_CLEANUP_BYPASS_PERMISSIONS list defines what account permissions are required to bypass this strip.

evennia.utils.utils.copy_word_case(base_word, new_word)[源代码]

Converts a word to use the same capitalization as a first word.

参数
  • base_word (str) – A word to get the capitalization from.

  • new_word (str) – A new word to capitalize in the same way as base_word.

返回

str – The new_word with capitalization matching the first word.

提示

This is meant for words. Longer sentences may get unexpected results.

If the two words have a mix of capital/lower letters _and_ new_word is longer than base_word, the excess will retain its original case.

evennia.utils.utils.run_in_main_thread(function_or_method, *args, **kwargs)[源代码]

Force a callable to execute in the main Evennia thread. This is only relevant when calling code from e.g. web views, which run in a separate threadpool. Use this to avoid race conditions.

参数
  • function_or_method (callable) – A function or method to fire.

  • *args – Will be passed into the callable.

  • **kwargs – Will be passed into the callable.

evennia.utils.utils.int2str(number, adjective=False)[源代码]

Convert a number to an English string for better display; so 1 -> one, 2 -> two etc up until 12, after which it will be ‘13’, ‘14’ etc.

参数
  • number (int) – The number to convert. Floats will be converted to ints.

  • adjective (bool) – If True, map 1->1st, 2->2nd etc. If unset or False, map 1->one, 2->two etc. up to twelve.

返回

str – The number expressed as a string.

evennia.utils.utils.str2int(number)[源代码]

Converts a string to an integer.

参数

number (str) – The string to convert. It can be a digit such as “1”, or a number word such as “one”.

返回

int – The string represented as an integer.

evennia.utils.utils.match_ip(address, pattern) → bool[源代码]

Check if an IP address matches a given pattern. The pattern can be a single IP address such as 8.8.8.8 or a CIDR-formatted subnet like 10.0.0.0/8

IPv6 is supported to, with CIDR-subnets looking like 2001:db8::/48

参数
  • address (str) – The source address being checked.

  • pattern (str) – The single IP address or subnet to check against.

返回

result (bool) – Whether it was a match or not.

evennia.utils.utils.ip_from_request(request, exclude=None) → str[源代码]

Retrieves the IP address from a web Request, while respecting X-Forwarded-For and settings.UPSTREAM_IPS.

参数
  • request (django Request or twisted.web.http.Request) – The web request.

  • exclude – (list, optional): A list of IP addresses to exclude from the check. If left none, then settings.UPSTREAM_IPS will be used.

返回

ip (str) – The IP address the request originated from.

evennia.utils.utils.value_is_integer(value)[源代码]

Determines if a value can be type-cast to an integer.

参数

value (any) – The value to check.

返回

result (bool) – Whether it can be type-cast to an integer or not.