Refactor code for readability and compatibility.

This commit is contained in:
Griatch 2017-01-27 00:19:27 +01:00
parent a09835049b
commit c6d9c0619e
43 changed files with 129 additions and 112 deletions

View file

@ -103,6 +103,7 @@ def _create_version():
try:
version = "%s (rev %s)" % (version, check_output("git rev-parse --short HEAD", shell=True, cwd=root, stderr=STDOUT).strip())
except (IOError, CalledProcessError):
# ignore if we cannot get to git
pass
return version

View file

@ -383,7 +383,7 @@ def get_and_merge_cmdsets(caller, session, player, obj, callertype):
except Exception:
_msg_err(caller, _ERROR_CMDSETS)
raise
raise ErrorReported
#raise ErrorReported
# Main command-handler function
@ -565,7 +565,7 @@ def cmdhandler(called_by, raw_string, _testing=False, callertype="session", sess
syscmd.matches = matches
else:
# fall back to default error handling
sysarg = yield _SEARCH_AT_RESULT([match[2] for match in matches], caller, query=match[0])
sysarg = yield _SEARCH_AT_RESULT([match[2] for match in matches], caller, query=matches[0][0])
raise ExecSystemCommand(syscmd, sysarg)
if len(matches) == 1:

View file

@ -40,21 +40,21 @@ class _CmdSetMeta(type):
the cmdset class.
"""
def __init__(mcs, *args, **kwargs):
def __init__(cls, *args, **kwargs):
"""
Fixes some things in the cmdclass
"""
# by default we key the cmdset the same as the
# name of its class.
if not hasattr(mcs, 'key') or not mcs.key:
mcs.key = mcs.__name__
mcs.path = "%s.%s" % (mcs.__module__, mcs.__name__)
if not hasattr(cls, 'key') or not cls.key:
cls.key = cls.__name__
cls.path = "%s.%s" % (cls.__module__, cls.__name__)
if not type(mcs.key_mergetypes) == dict:
mcs.key_mergetypes = {}
if not type(cls.key_mergetypes) == dict:
cls.key_mergetypes = {}
super(_CmdSetMeta, mcs).__init__(*args, **kwargs)
super(_CmdSetMeta, cls).__init__(*args, **kwargs)
class CmdSet(with_metaclass(_CmdSetMeta, object)):
@ -511,6 +511,7 @@ class CmdSet(with_metaclass(_CmdSetMeta, object)):
ic = self.system_commands.index(cmd)
del self.system_commands[ic]
except ValueError:
# ignore error
pass
else:
self.commands = [oldcmd for oldcmd in self.commands if oldcmd != cmd]

View file

@ -490,6 +490,7 @@ class CmdSetHandler(object):
storage.remove(cset.path)
updated = True
except ValueError:
# nothing to remove
pass
if updated:
self.obj.cmdset_storage = storage
@ -498,6 +499,7 @@ class CmdSetHandler(object):
try:
self.cmdset_stack.remove(cset)
except ValueError:
# nothing to remove
pass
# re-sync the cmdsethandler.
self.update()

View file

@ -12,7 +12,7 @@ from evennia.utils.utils import is_iter, fill, lazy_property, make_iter
from future.utils import with_metaclass
def _init_command(mcs, **kwargs):
def _init_command(cls, **kwargs):
"""
Helper command.
Makes sure all data are stored as lowercase and
@ -26,60 +26,60 @@ def _init_command(mcs, **kwargs):
for i in range(len(kwargs)):
# used for dynamic creation of commands
key, value = kwargs.popitem()
setattr(mcs, key, value)
setattr(cls, key, value)
mcs.key = mcs.key.lower()
if mcs.aliases and not is_iter(mcs.aliases):
cls.key = cls.key.lower()
if cls.aliases and not is_iter(cls.aliases):
try:
mcs.aliases = [str(alias).strip().lower()
for alias in mcs.aliases.split(',')]
cls.aliases = [str(alias).strip().lower()
for alias in cls.aliases.split(',')]
except Exception:
mcs.aliases = []
mcs.aliases = list(set(alias for alias in mcs.aliases
if alias and alias != mcs.key))
cls.aliases = []
cls.aliases = list(set(alias for alias in cls.aliases
if alias and alias != cls.key))
# optimization - a set is much faster to match against than a list
mcs._matchset = set([mcs.key] + mcs.aliases)
cls._matchset = set([cls.key] + cls.aliases)
# optimization for looping over keys+aliases
mcs._keyaliases = tuple(mcs._matchset)
cls._keyaliases = tuple(cls._matchset)
# by default we don't save the command between runs
if not hasattr(mcs, "save_for_next"):
mcs.save_for_next = False
if not hasattr(cls, "save_for_next"):
cls.save_for_next = False
# pre-process locks as defined in class definition
temp = []
if hasattr(mcs, 'permissions'):
mcs.locks = mcs.permissions
if not hasattr(mcs, 'locks'):
if hasattr(cls, 'permissions'):
cls.locks = cls.permissions
if not hasattr(cls, 'locks'):
# default if one forgets to define completely
mcs.locks = "cmd:all()"
if not "cmd:" in mcs.locks:
mcs.locks = "cmd:all();" + mcs.locks
for lockstring in mcs.locks.split(';'):
cls.locks = "cmd:all()"
if not "cmd:" in cls.locks:
cls.locks = "cmd:all();" + cls.locks
for lockstring in cls.locks.split(';'):
if lockstring and not ':' in lockstring:
lockstring = "cmd:%s" % lockstring
temp.append(lockstring)
mcs.lock_storage = ";".join(temp)
cls.lock_storage = ";".join(temp)
if hasattr(mcs, 'arg_regex') and isinstance(mcs.arg_regex, basestring):
mcs.arg_regex = re.compile(r"%s" % mcs.arg_regex, re.I + re.UNICODE)
if not hasattr(mcs, "auto_help"):
mcs.auto_help = True
if not hasattr(mcs, 'is_exit'):
mcs.is_exit = False
if not hasattr(mcs, "help_category"):
mcs.help_category = "general"
mcs.help_category = mcs.help_category.lower()
if hasattr(cls, 'arg_regex') and isinstance(cls.arg_regex, basestring):
cls.arg_regex = re.compile(r"%s" % cls.arg_regex, re.I + re.UNICODE)
if not hasattr(cls, "auto_help"):
cls.auto_help = True
if not hasattr(cls, 'is_exit'):
cls.is_exit = False
if not hasattr(cls, "help_category"):
cls.help_category = "general"
cls.help_category = cls.help_category.lower()
class CommandMeta(type):
"""
The metaclass cleans up all properties on the class
"""
def __init__(mcs, *args, **kwargs):
_init_command(mcs, **kwargs)
super(CommandMeta, mcs).__init__(*args, **kwargs)
def __init__(cls, *args, **kwargs):
_init_command(cls, **kwargs)
super(CommandMeta, cls).__init__(*args, **kwargs)
# The Command class is the basic unit of an Evennia command; when
# defining new commands, the admin subclass this class and

View file

@ -203,7 +203,8 @@ def purge_processor(caller):
del caller.ndb.batch_stackptr
del caller.ndb.batch_pythonpath
del caller.ndb.batch_batchmode
except:
except Exception:
# something might have already been erased; it's not critical
pass
# clear everything back to the state before the batch call
if caller.ndb.batch_cmdset_backup:

View file

@ -1355,10 +1355,12 @@ def _convert_from_string(cmd, strobj):
try:
return int(obj)
except ValueError:
# obj cannot be converted to int - that's fine
pass
try:
return float(obj)
except ValueError:
# obj cannot be converted to float - that's fine
pass
# iterables
if obj.startswith('[') and obj.endswith(']'):
@ -1983,6 +1985,7 @@ class CmdExamine(ObjManipCommand):
# we have to protect this since many objects don't have sessions.
all_cmdsets.extend([(cmdset.key, cmdset) for cmdset in obj.get_session(obj.sessions.get()).cmdset.all()])
except (TypeError, AttributeError):
# an error means we are merging an object without a session
pass
all_cmdsets = [cmdset for cmdset in dict(all_cmdsets).values()]
all_cmdsets.sort(key=lambda x: x.priority, reverse=True)

View file

@ -316,10 +316,7 @@ class CmdScripts(COMMAND_DEFAULT_CLASS):
if self.switches and self.switches[0] in ('stop', 'del', 'delete', 'kill'):
# we want to delete something
if not scripts:
string = "No scripts/objects matching '%s'. " % args
string += "Be more specific."
elif len(scripts) == 1:
if len(scripts) == 1:
# we have a unique match!
if 'kill' in self.switches:
string = "Killing script '%s'" % scripts[0].key

View file

@ -105,7 +105,7 @@ def create_guest_player(session):
if not PlayerDB.objects.filter(username__iexact=playername):
break
playername = None
if playername == None:
if playername is None:
session.msg("All guest accounts are in use. Please try again later.")
return True, None
@ -126,8 +126,7 @@ def create_guest_player(session):
# we won't see any errors at all.
session.msg("An error occurred. Please e-mail an admin if the problem persists.")
logger.log_trace()
finally:
return True, new_player
raise
def create_normal_player(session, name, password):

View file

@ -79,6 +79,7 @@ class ChannelCommand(command.Command):
try:
self.history_start = int(arg) if arg else 0
except ValueError:
# if no valid number was given, ignore it
pass
self.args = (channelname.strip(), msg.strip())

View file

@ -401,6 +401,7 @@ class ChannelDBManager(TypedObjectManager):
dbref = int(ostring.strip('#'))
channels = self.filter(id=dbref)
except Exception:
# Usually because we couldn't convert to int - not a dbref
pass
if not channels:
# no id match. Search on the key.

View file

@ -612,6 +612,7 @@ class CmdEvaluate(CmdTradeBase):
ind = int(self.args)
self.args = ind - 1
except Exception:
# not a valid index - ignore
pass
offer = self.tradehandler.search(self.args)

View file

@ -51,6 +51,7 @@ CONNECTION_SCREEN = ""
try:
CONNECTION_SCREEN = ansi.parse_ansi(utils.random_string_from_module(CONNECTION_SCREEN_MODULE))
except Exception:
# malformed connection screen or no screen given
pass
if not CONNECTION_SCREEN:
CONNECTION_SCREEN = "\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid."

View file

@ -39,7 +39,7 @@ class CmdNudge(Command):
rand = random.random()
if rand < 0.5:
self.caller.msg("You nudge at the lid. It seems stuck.")
elif 0.5 <= rand < 0.7:
elif rand < 0.7:
self.caller.msg("You move the lid back and forth. It won't budge.")
else:
self.caller.msg("You manage to get a nail under the lid.")

View file

@ -344,6 +344,7 @@ class LightSource(TutorialObject):
self.location.msg_contents("A %s on the floor flickers and dies." % self.key)
self.location.location.check_light_state()
except AttributeError:
# Mainly happens if we happen to be in a None location
pass
self.delete()
@ -364,6 +365,7 @@ class LightSource(TutorialObject):
# maybe we are directly in the room
self.location.check_light_state()
except AttributeError:
# we are in a None location
pass
finally:
# start the burn timer. When it runs out, self._burnout

View file

@ -62,15 +62,18 @@ MSSPTable = {
# Protocols set to 1 or 0)
"ANSI": "1",
"GMCP": "0",
"GMCP": "1",
"ATCP": "0",
"MCCP": "0",
"MCP": "0",
"MSDP": "0",
"MSP": "0",
"MXP": "0",
"PUEBLO": "0",
"SSL": "1",
"UTF-8": "1",
"VT100": "0",
"ZMP": "0",
"XTERM 256 COLORS": "0",
# Commercial set to 1 or 0)
@ -111,12 +114,4 @@ MSSPTable = {
"TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both"
"WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original"
# Protocols (only change if you added/removed something manually)
"ATCP": "0",
"MSDP": "0",
"MCCP": "1",
"SSL": "1",
"UTF-8": "1",
"ZMP": "0",
"XTERM 256 COLORS": "0"}
}

View file

@ -539,6 +539,7 @@ def holds(accessing_obj, accessed_obj, *args, **kwargs):
if check_holds(accessed_obj.dbid):
return True
except Exception:
# we need to catch any trouble here
pass
return hasattr(accessed_obj, "obj") and check_holds(accessed_obj.obj.dbid)
if len(args) == 1:

View file

@ -409,6 +409,7 @@ class ObjectDBManager(TypedObjectManager):
try:
matches = [matches[match_number]]
except IndexError:
# match number not matching anything
pass
# return a list (possibly empty)
return matches

View file

@ -242,12 +242,14 @@ class ObjectDB(TypedObject):
return
elif loc == self:
raise RuntimeError
elif loc == None:
elif loc is None:
raise RuntimeWarning
return is_loc_loop(loc.db_location, depth + 1)
try:
is_loc_loop(location)
except RuntimeWarning:
# we caught a infitite location loop!
# (location1 is in location2 which is in location1 ...)
pass
# if we get to this point we are ready to change location

View file

@ -83,7 +83,7 @@ class ObjectSessionHandler(object):
if sessid:
sessions = [_SESSIONS[sessid] if sessid in _SESSIONS else None] if sessid in self._sessid_cache else []
else:
sessions = [_SESSIONS[sessid] if sessid in _SESSIONS else None for sessid in self._sessid_cache]
sessions = [_SESSIONS[ssid] if ssid in _SESSIONS else None for ssid in self._sessid_cache]
if None in sessions:
# this happens only if our cache has gone out of sync with the SessionHandler.
self._recache()

View file

@ -409,12 +409,14 @@ class DefaultPlayer(with_metaclass(TypeclassBase, PlayerDB)):
try:
from_obj.at_msg_send(text=text, to_obj=self, **kwargs)
except Exception:
# this may not be assigned.
pass
try:
if not self.at_msg_receive(text=text, **kwargs):
# abort message to this player
return
except Exception:
# this may not be assigned.
pass
kwargs["options"] = options

View file

@ -139,6 +139,7 @@ class ScriptDB(TypedObject):
try:
value = _GA(value, "dbobj")
except AttributeError:
# deprecated ...
pass
if isinstance(value, (basestring, int)):
from evennia.objects.models import ObjectDB

View file

@ -46,7 +46,7 @@ class ScriptHandler(object):
repeats = script.repeats
try:
next_repeat = script.time_until_next_repeat()
except:
except Exception:
next_repeat = "?"
string += _("\n '%(key)s' (%(next_repeat)s/%(interval)s, %(repeats)s repeats): %(desc)s") % \
{"key": script.key, "next_repeat": next_repeat,

View file

@ -100,7 +100,7 @@ class ExtendedLoopingCall(LoopingCall):
if self.start_delay:
self.start_delay = None
self.starttime = self.clock.seconds()
super(ExtendedLoopingCall, self).__call__()
LoopingCall.__call__(self)
def force_repeat(self):
"""
@ -210,6 +210,7 @@ class DefaultScript(ScriptBase):
try:
self.db_obj.msg(estring)
except Exception:
# we must not crash inside the errback, even if db_obj is None.
pass
logger.log_err(estring)

View file

@ -405,6 +405,7 @@ def evennia_version():
import evennia
version = evennia.__version__
except ImportError:
# even if evennia is not found, we should not crash here.
pass
try:
rev = check_output(
@ -412,6 +413,7 @@ def evennia_version():
shell=True, cwd=EVENNIA_ROOT, stderr=STDOUT).strip()
version = "%s (rev %s)" % (version, rev)
except (IOError, CalledProcessError):
# move on if git is not answering
pass
return version
@ -520,7 +522,7 @@ def create_settings_file(init=True):
if not init:
# if not --init mode, settings file may already exist from before
if os.path.exists(settings_path):
inp = raw_input("server/conf/settings.py already exists. "
inp = input("server/conf/settings.py already exists. "
"Do you want to reset it? y/[N]> ")
if not inp.lower() == 'y':
print ("Aborted.")
@ -659,14 +661,13 @@ def get_pid(pidfile):
pidfile (str): The path of the pid file.
Returns:
pid (str): The process id.
pid (str or None): The process id.
"""
pid = None
if os.path.exists(pidfile):
f = open(pidfile, 'r')
pid = f.read()
return pid
with open(pidfile, 'r') as f:
pid = f.read()
return pid
def del_pid(pidfile):
@ -722,6 +723,7 @@ def kill(pidfile, signal=SIG, succmsg="", errmsg="",
SetConsoleCtrlHandler(None, True)
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)
except KeyboardInterrupt:
# We must catch and ignore the interrupt sent.
pass
else:
# Linux can send the SIGINT signal directly
@ -986,6 +988,8 @@ def run_dummyrunner(number_of_dummies):
try:
call(cmdstr, env=getenv())
except KeyboardInterrupt:
# this signals the dummyrunner to stop cleanly and should
# not lead to a traceback here.
pass

View file

@ -133,13 +133,16 @@ class Mssp(object):
"ANSI": "1",
"GMCP": "0",
"ATCP": "0",
"MCCP": "0",
"MCP": "0",
"MSDP": "0",
"MSP": "0",
"MXP": "0",
"PUEBLO": "0",
"SSL": "1",
"UTF-8": "1",
"ZMP": "0",
"VT100": "0",
"XTERM 256 COLORS": "0",
@ -180,16 +183,7 @@ class Mssp(object):
"ROLEPLAYING": "None", # "None", "Accepted", "Encouraged", "Enforced"
"TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both"
"WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original"
# Protocols (only change if you added/removed something manually)
"ATCP": "0",
"MSDP": "0",
"MCCP": "1",
"SSL": "1",
"UTF-8": "1",
"ZMP": "0",
"XTERM 256 COLORS": "0"}
}
# update the static table with the custom one
if MSSPTable_CUSTOM:

View file

@ -364,6 +364,7 @@ class PortalSessionHandler(SessionHandler):
self.data_out(session, text=[[_ERROR_MAX_CHAR], {}])
return
except Exception:
# if there is a problem to send, we continue
pass
if session:
now = time()

View file

@ -364,6 +364,7 @@ class TelnetOOB(object):
try:
structure = json.loads(structure)
except ValueError:
# maybe the structure is not json-serialized at all
pass
args, kwargs = [], {}
if hasattr(structure, "__iter__"):

View file

@ -89,6 +89,7 @@ class Ttype(object):
try:
option = "".join(option).lstrip(IS)
except TypeError:
# option is not on a suitable form for joining
pass
if self.ttype_step == 0:

View file

@ -204,7 +204,7 @@ class WebSocketClient(Protocol, Session):
kwargs["options"].update({"send_prompt": True})
self.send_text(*args, **kwargs)
def send_default(session, cmdname, *args, **kwargs):
def send_default(self, cmdname, *args, **kwargs):
"""
Data Evennia -> User.
@ -219,4 +219,4 @@ class WebSocketClient(Protocol, Session):
"""
if not cmdname == "options":
session.sendLine(json.dumps([cmdname, args, kwargs]))
self.sendLine(json.dumps([cmdname, args, kwargs]))

View file

@ -76,6 +76,7 @@ class WebClient(resource.Resource):
try:
del self.requests[csessid]
except KeyError:
# nothing left to delete
pass
def _keepalive(self):

View file

@ -310,7 +310,7 @@ class ServerSession(Session):
cchan = ChannelDB.objects.get_channel(cchan[0])
cchan.msg("[%s]: %s" % (cchan.key, message))
except Exception:
pass
logger.log_trace()
logger.log_info(message)
def get_client_size(self):

View file

@ -696,6 +696,7 @@ try:
import django_extensions
INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',)
except ImportError:
# Django extensions are not installed in all distros.
pass
#######################################################################

View file

@ -286,7 +286,7 @@ class TagHandler(object):
for keystr in make_iter(key):
# note - the _getcache call removes case sensitivity for us
ret.extend([tag if return_tagobj else to_str(tag.db_key)
for tag in self._getcache(key, category)])
for tag in self._getcache(keystr, category)])
return ret[0] if len(ret) == 1 else (ret if ret else default)
def remove(self, key, category=None):
@ -355,7 +355,6 @@ class TagHandler(object):
return [(to_str(tag.db_key), to_str(tag.db_category)) for tag in tags]
else:
return [to_str(tag.db_key) for tag in tags]
return []
def __str__(self):
return ",".join(self.all())

View file

@ -575,6 +575,7 @@ def _on_raw(func_name):
else:
args.insert(0, string)
except IndexError:
# just skip out if there are no more strings
pass
result = getattr(self._raw_string, func_name)(*args, **kwargs)
if isinstance(result, basestring):
@ -850,6 +851,7 @@ class ANSIString(with_metaclass(ANSIMeta, unicode)):
try:
string += self._raw_string[i]
except IndexError:
# raw_string not long enough
pass
if i is not None:
append_tail = self._get_interleving(self._char_indexes.index(i) + 1)

View file

@ -115,7 +115,7 @@ def create_object(typeclass=None, key=None, location=None,
# store the call signature for the signal
new_object._createdict = {"key":key, "location":location, "destination":destination,
"home":home, "typeclass":typeclass.path, "permissions":permissions,
"locks":locks, "aliases":aliases, "tags": tags, "destination":destination,
"locks":locks, "aliases":aliases, "tags": tags,
"report_to":report_to, "nohome":nohome}
# this will trigger the save signal which in turn calls the
# at_first_save hook on the typeclass, where the _createdict can be

View file

@ -809,7 +809,7 @@ class EvEditor(object):
formatting information.
"""
if buf == None:
if buf is None:
buf = self._buffer
if is_iter(buf):
buf = "\n".join(buf)

View file

@ -159,14 +159,14 @@ class ANSITextWrapper(TextWrapper):
"""
# ignore expand_tabs/replace_whitespace until ANSISTring handles them
return text
if self.expand_tabs:
text = text.expandtabs()
if self.replace_whitespace:
if isinstance(text, str):
text = text.translate(self.whitespace_trans)
elif isinstance(text, _unicode):
text = text.translate(self.unicode_whitespace_trans)
return text
# if self.expand_tabs:
# text = text.expandtabs()
# if self.replace_whitespace:
# if isinstance(text, str):
# text = text.translate(self.whitespace_trans)
# elif isinstance(text, _unicode):
# text = text.translate(self.unicode_whitespace_trans)
# return text
def _split(self, text):

View file

@ -134,10 +134,6 @@ class SharedMemoryModelBase(ModelBase):
"Setter only used on foreign key relations, allows setting with #dbref"
if _GA(cls, "_is_deleted"):
raise ObjectDoesNotExist("Cannot set %s to %s: Hosting object was already deleted!" % (fname, value))
try:
value = _GA(value, "dbobj")
except AttributeError:
pass
if isinstance(value, (basestring, int)):
value = to_str(value, force_string=True)
if (value.isdigit() or value.startswith("#")):
@ -273,6 +269,7 @@ class SharedMemoryModel(with_metaclass(SharedMemoryModelBase, Model)):
# at first initialization
instance.at_init()
except AttributeError:
# The at_init hook is not assigned to all entities
pass
@classmethod

View file

@ -212,7 +212,7 @@ class PickledObjectField(models.Field):
if value is not None:
try:
value = dbsafe_decode(value, self.compress)
except:
except Exception:
# If the value is a definite pickle; and an error is raised in
# de-pickling it should be allowed to propogate.
if isinstance(value, PickledObject):

View file

@ -430,12 +430,12 @@ class PrettyTable(object):
##############################
def _get_field_names(self):
return self._field_names
"""The names of the fields
Arguments:
fields - list or tuple of field names"""
return self._field_names
def _set_field_names(self, val):
val = [self._unicode(x) for x in val]
self._validate_option("field_names", val)

View file

@ -99,6 +99,7 @@ def http_headers(s):
key, value = [i.strip() for i in line.split(":", 1)]
d[key] = value
except ValueError:
# malformed header, skip it
pass
return d
@ -257,8 +258,8 @@ def parse_hybi07_frames(buf):
if header & 0x70:
# At least one of the reserved flags is set. Pork chop sandwiches!
raise WSException("Reserved flag in HyBi-07 frame (%d)" % header)
frames.append(("", CLOSE))
return frames, buf
#frames.append(("", CLOSE))
#return frames, buf
# Get the opcode, and translate it to a local enum which we actually
# care about.

View file

@ -703,6 +703,7 @@ def to_unicode(obj, encoding='utf-8', force_string=False):
obj = unicode(obj, alt_encoding)
return obj
except UnicodeDecodeError:
# if we still have an error, give up
pass
raise Exception("Error: '%s' contains invalid character(s) not in %s." % (obj, encoding))
return obj
@ -744,6 +745,7 @@ def to_str(obj, encoding='utf-8', force_string=False):
obj = obj.encode(alt_encoding)
return obj
except UnicodeEncodeError:
# if we still have an error, give up
pass
# if we get to this point we have not found any way to convert this string. Try to parse it manually,
@ -926,6 +928,7 @@ def clean_object_caches(obj):
try:
_SA(obj, "_contents_cache", None)
except AttributeError:
# if the cache cannot be reached, move on anyway
pass
# on-object property cache
@ -935,6 +938,7 @@ def clean_object_caches(obj):
hashid = _GA(obj, "hashid")
_TYPECLASSMODELS._ATTRIBUTE_CACHE[hashid] = {}
except AttributeError:
# skip caching
pass
@ -1273,9 +1277,9 @@ def fuzzy_import_from_module(path, variable, default=None, defaultpaths=None):
paths = [path] + make_iter(defaultpaths)
for modpath in paths:
try:
mod = import_module(path)
mod = import_module(modpath)
except ImportError as ex:
if not str(ex).startswith ("No module named %s" % path):
if not str(ex).startswith ("No module named %s" % modpath):
# this means the module was found but it
# triggers an ImportError on import.
raise ex
@ -1521,13 +1525,11 @@ def get_evennia_pids():
portal_pidfile = os.path.join(settings.GAME_DIR, 'portal.pid')
server_pid, portal_pid = None, None
if os.path.exists(server_pidfile):
f = open(server_pidfile, 'r')
server_pid = f.read()
f.close()
with open(server_pidfile, 'r') as f:
server_pid = f.read()
if os.path.exists(portal_pidfile):
f = open(portal_pidfile, 'r')
portal_pid = f.read()
f.close()
with open(portal_pidfile, 'r') as f:
portal_pid = f.read()
if server_pid and portal_pid:
return int(server_pid), int(portal_pid)
return None, None