Run 2to3.

This commit is contained in:
Ryan Stein 2017-10-29 13:40:30 -04:00
parent a5a8d9dd57
commit 6fa280b9fd
157 changed files with 976 additions and 976 deletions

View file

@ -15,16 +15,16 @@ Server - (AMP server) Handles all mud operations. The server holds its own list
at startup and when a session connects/disconnects
"""
from __future__ import print_function
# imports needed on both server and portal side
import os
import time
from collections import defaultdict, namedtuple
from itertools import count
from cStringIO import StringIO
from io import StringIO
try:
import cPickle as pickle
import pickle as pickle
except ImportError:
import pickle
from twisted.protocols import amp

View file

@ -9,7 +9,7 @@ and portal through the evennia_runner. Run without arguments to get a
menu. Run the script with the -h flag to see usage information.
"""
from __future__ import print_function
from builtins import input, range
import os
@ -535,7 +535,7 @@ def create_settings_file(init=True, secret_settings=False):
if not init:
# if not --init mode, settings file may already exist from before
if os.path.exists(settings_path):
inp = input("%s already exists. Do you want to reset it? y/[N]> " % settings_path)
inp = eval(input("%s already exists. Do you want to reset it? y/[N]> " % settings_path))
if not inp.lower() == 'y':
print ("Aborted.")
return
@ -601,9 +601,9 @@ def check_database():
# Check so a database exists and is accessible
from django.db import connection
tables = connection.introspection.get_table_list(connection.cursor())
if not tables or not isinstance(tables[0], basestring): # django 1.8+
if not tables or not isinstance(tables[0], str): # django 1.8+
tables = [tableinfo.name for tableinfo in tables]
if tables and u'accounts_accountdb' in tables:
if tables and 'accounts_accountdb' in tables:
# database exists and seems set up. Initialize evennia.
evennia._init()
# Try to get Account#1
@ -632,7 +632,7 @@ def check_database():
res = ""
while res.upper() != "Y":
# ask for permission
res = input("Continue [Y]/N: ")
res = eval(input("Continue [Y]/N: "))
if res.upper() == "N":
sys.exit()
elif not res:
@ -993,9 +993,9 @@ def list_settings(keys):
# a specific key
table = evtable.EvTable(width=131)
keys = [key.upper() for key in keys]
confs = dict((key, var) for key, var in evsettings.__dict__.items()
confs = dict((key, var) for key, var in list(evsettings.__dict__.items())
if key in keys)
for key, val in confs.items():
for key, val in list(confs.items()):
table.add_row(key, str(val))
print(table)
@ -1009,18 +1009,18 @@ def run_menu():
# menu loop
print(MENU)
inp = input(" option > ")
inp = eval(input(" option > "))
# quitting and help
if inp.lower() == 'q':
return
elif inp.lower() == 'h':
print(HELP_ENTRY)
input("press <return> to continue ...")
eval(input("press <return> to continue ..."))
continue
elif inp.lower() in ('v', 'i', 'a'):
print(show_version_info(about=True))
input("press <return> to continue ...")
eval(input("press <return> to continue ..."))
continue
# options

View file

@ -14,13 +14,13 @@ upon returning, or not. A process returning != 0 will always stop, no
matter the value of this file.
"""
from __future__ import print_function
import os
import sys
from argparse import ArgumentParser
from subprocess import Popen
import Queue
import thread
import queue
import _thread
import evennia
try:
@ -143,7 +143,7 @@ def start_services(server_argv, portal_argv, doexit=False):
and then restarts them when they finish.
"""
global SERVER, PORTAL
processes = Queue.Queue()
processes = queue.Queue()
def server_waiter(queue):
try:
@ -167,7 +167,7 @@ def start_services(server_argv, portal_argv, doexit=False):
try:
if not doexit and get_restart_mode(PORTAL_RESTART) == "True":
# start portal as interactive, reloadable thread
PORTAL = thread.start_new_thread(portal_waiter, (processes, ))
PORTAL = _thread.start_new_thread(portal_waiter, (processes, ))
else:
# normal operation: start portal as a daemon;
# we don't care to monitor it for restart
@ -182,7 +182,7 @@ def start_services(server_argv, portal_argv, doexit=False):
SERVER = Popen(server_argv, env=getenv())
else:
# start server as a reloadable thread
SERVER = thread.start_new_thread(server_waiter, (processes, ))
SERVER = _thread.start_new_thread(server_waiter, (processes, ))
except IOError as e:
print(PROCESS_IOERROR.format(component="Server", traceback=e))
return
@ -207,14 +207,14 @@ def start_services(server_argv, portal_argv, doexit=False):
if (message == "server_stopped" and int(rc) == 0 and
get_restart_mode(SERVER_RESTART) in ("True", "reload", "reset")):
print(PROCESS_RESTART.format(component="Server"))
SERVER = thread.start_new_thread(server_waiter, (processes, ))
SERVER = _thread.start_new_thread(server_waiter, (processes, ))
continue
# normally the portal is not reloaded since it's run as a daemon.
if (message == "portal_stopped" and int(rc) == 0 and
get_restart_mode(PORTAL_RESTART) == "True"):
print(PROCESS_RESTART.format(component="Portal"))
PORTAL = thread.start_new_thread(portal_waiter, (processes, ))
PORTAL = _thread.start_new_thread(portal_waiter, (processes, ))
continue
break
except ReactorNotRunning:

View file

@ -5,7 +5,7 @@ other things.
Everything starts at handle_setup()
"""
from __future__ import print_function
import time
from django.conf import settings

View file

@ -185,11 +185,11 @@ def client_options(session, *args, **kwargs):
return {0: int(val)}
def validate_bool(val):
if isinstance(val, basestring):
if isinstance(val, str):
return True if val.lower() in ("true", "on", "1") else False
return bool(val)
for key, value in kwargs.iteritems():
for key, value in kwargs.items():
key = key.lower()
if key == "client":
flags["CLIENTNAME"] = to_str(value)
@ -254,7 +254,7 @@ def get_inputfuncs(session, *args, **kwargs):
So we get it from the sessionhandler.
"""
inputfuncsdict = dict((key, func.__doc__) for key, func
in session.sessionhandler.get_inputfuncs().iteritems())
in session.sessionhandler.get_inputfuncs().items())
session.msg(get_inputfuncs=inputfuncsdict)
@ -463,5 +463,5 @@ def webclient_options(session, *args, **kwargs):
session=session)
else:
# kwargs provided: persist them to the account object
for key, value in kwargs.iteritems():
for key, value in kwargs.items():
clientoptions[key] = value

View file

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations

View file

@ -11,7 +11,7 @@ manager's conf() method.
from builtins import object
try:
import cPickle as pickle
import pickle as pickle
except ImportError:
import pickle

View file

@ -191,7 +191,7 @@ class Mssp(object):
self.mssp_table.update(MSSPTable_CUSTOM)
varlist = ''
for variable, value in self.mssp_table.items():
for variable, value in list(self.mssp_table.items()):
if callable(value):
value = value()
if utils.is_iter(value):

View file

@ -7,7 +7,7 @@ sets up all the networking features. (this is done automatically
by game/evennia.py).
"""
from __future__ import print_function
from builtins import object
import time

View file

@ -1,8 +1,8 @@
"""
Sessionhandler for portal sessions
"""
from __future__ import print_function
from __future__ import division
import time
from collections import deque, namedtuple
@ -141,7 +141,7 @@ class PortalSessionHandler(SessionHandler):
if self.portal.amp_protocol:
# we only send sessdata that should not have changed
# at the server level at this point
sessdata = dict((key, val) for key, val in sessdata.items() if key in ("protocol_key",
sessdata = dict((key, val) for key, val in list(sessdata.items()) if key in ("protocol_key",
"address",
"sessid",
"csessid",
@ -188,7 +188,7 @@ class PortalSessionHandler(SessionHandler):
# we set a watchdog to stop self.disconnect from deleting
# sessions while we are looping over them.
sessionhandler._disconnect_all = True
for session in sessionhandler.values():
for session in list(sessionhandler.values()):
session.disconnect()
del sessionhandler._disconnect_all
@ -253,7 +253,7 @@ class PortalSessionHandler(SessionHandler):
reason (str, optional): Motivation for disconnect.
"""
for session in self.values():
for session in list(self.values()):
session.disconnect(reason)
del session
self.clear()
@ -336,7 +336,7 @@ class PortalSessionHandler(SessionHandler):
send command.
"""
for session in self.values():
for session in list(self.values()):
self.data_out(session, text=[[message], {}])
def data_in(self, session, **kwargs):
@ -412,7 +412,7 @@ class PortalSessionHandler(SessionHandler):
# distribute outgoing data to the correct session methods.
if session:
for cmdname, (cmdargs, cmdkwargs) in kwargs.iteritems():
for cmdname, (cmdargs, cmdkwargs) in kwargs.items():
funcname = "send_%s" % cmdname.strip().lower()
if hasattr(session, funcname):
# better to use hassattr here over try..except

View file

@ -8,7 +8,7 @@ login procedure of the game, tracks sessions etc.
Using standard ssh client,
"""
from __future__ import print_function
from builtins import object
import os
import re

View file

@ -3,7 +3,7 @@ This is a simple context factory for auto-creating
SSL keys and certificates.
"""
from __future__ import print_function
import os
import sys

View file

@ -208,7 +208,7 @@ class TelnetOOB(object):
msdp_kwargs="".join("%s%s%s%s"
% (MSDP_VAR, key, MSDP_VAL,
json.dumps(val))
for key, val in kwargs.iteritems()))
for key, val in kwargs.items()))
msdp_string = msdp_args + msdp_kwargs
@ -316,7 +316,7 @@ class TelnetOOB(object):
cmds = {}
# merge matching table/array/variables together
for key, table in tables.iteritems():
for key, table in tables.items():
args, kwargs = [], table
if key in arrays:
args.extend(arrays.pop(key))
@ -324,13 +324,13 @@ class TelnetOOB(object):
args.append(variables.pop(key))
cmds[key] = [args, kwargs]
for key, arr in arrays.iteritems():
for key, arr in arrays.items():
args, kwargs = arr, {}
if key in variables:
args.append(variables.pop(key))
cmds[key] = [args, kwargs]
for key, var in variables.iteritems():
for key, var in variables.items():
cmds[key] = [[var], {}]
# print("msdp data in:", cmds) # DEBUG
@ -374,7 +374,7 @@ class TelnetOOB(object):
args, kwargs = [], {}
if hasattr(structure, "__iter__"):
if isinstance(structure, dict):
kwargs = {key: value for key, value in structure.iteritems() if key}
kwargs = {key: value for key, value in structure.items() if key}
else:
args = list(structure)
else:

View file

@ -87,7 +87,7 @@ class AjaxWebClient(resource.Resource):
now = time.time()
to_remove = []
keep_alives = ((csessid, remove) for csessid, (t, remove)
in self.last_alive.iteritems() if now - t > _KEEPALIVE)
in self.last_alive.items() if now - t > _KEEPALIVE)
for csessid, remove in keep_alives:
if remove:
# keepalive timeout. Line is dead.

View file

@ -30,8 +30,8 @@ in your settings. See utils.dummyrunner_actions.py
for instructions on how to define this module.
"""
from __future__ import print_function
from __future__ import division
from builtins import range
import sys

View file

@ -6,7 +6,7 @@ the script will append to this file if it already exists.
Call this module directly to plot the log (requires matplotlib and numpy).
"""
from __future__ import division
import os
import sys
import time

View file

@ -3,7 +3,7 @@ This is a little routine for viewing the sql queries that are executed by a give
query as well as count them for optimization testing.
"""
from __future__ import print_function
import sys
import os
#sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))

View file

@ -1,7 +1,7 @@
"""
Trace a message through the messaging system
"""
from __future__ import print_function
import time

View file

@ -7,7 +7,7 @@ sets up all the networking features. (this is done automatically
by evennia/server/server_runner.py).
"""
from __future__ import print_function
from builtins import object
import time
import sys
@ -131,7 +131,7 @@ def _server_maintenance():
# handle idle timeouts
if _IDLE_TIMEOUT > 0:
reason = _("idle timeout exceeded")
for session in (sess for sess in SESSIONS.values()
for session in (sess for sess in list(SESSIONS.values())
if (now - sess.cmd_last) > _IDLE_TIMEOUT):
if not session.account or not \
session.account.access(session.account, "noidletimeout", default=False):
@ -237,8 +237,8 @@ class Evennia(object):
"BASE_EXIT_TYPECLASS", "BASE_SCRIPT_TYPECLASS",
"BASE_CHANNEL_TYPECLASS")
# get previous and current settings so they can be compared
settings_compare = zip([ServerConfig.objects.conf(name) for name in settings_names],
[settings.__getattr__(name) for name in settings_names])
settings_compare = list(zip([ServerConfig.objects.conf(name) for name in settings_names],
[settings.__getattr__(name) for name in settings_names]))
mismatches = [i for i, tup in enumerate(settings_compare) if tup[0] and tup[1] and tup[0] != tup[1]]
if len(mismatches): # can't use any() since mismatches may be [0] which reads as False for any()
# we have a changed default. Import relevant objects and

View file

@ -141,7 +141,7 @@ class NAttributeHandler(object):
"""
if return_tuples:
return [(key, value) for (key, value) in self._store.items() if not key.startswith("_")]
return [(key, value) for (key, value) in list(self._store.items()) if not key.startswith("_")]
return [key for key in self._store if not key.startswith("_")]
@ -459,7 +459,7 @@ class ServerSession(Session):
def __unicode__(self):
"""Unicode representation"""
return u"%s" % str(self)
return "%s" % str(self)
# Dummy API hooks for use during non-loggedin operation

View file

@ -105,7 +105,7 @@ class Session(object):
the keys given by self._attrs_to_sync.
"""
return dict((key, value) for key, value in self.__dict__.items()
return dict((key, value) for key, value in list(self.__dict__.items())
if key in self._attrs_to_sync)
def load_sync_data(self, sessdata):
@ -117,7 +117,7 @@ class Session(object):
sessdata (dict): Session data dictionary.
"""
for propname, value in sessdata.items():
for propname, value in list(sessdata.items()):
setattr(self, propname, value)
def at_sync(self):

View file

@ -26,7 +26,7 @@ from evennia.utils.utils import (variable_from_module, is_iter,
from evennia.utils.inlinefuncs import parse_inlinefunc
try:
import cPickle as pickle
import pickle as pickle
except ImportError:
import pickle
@ -145,7 +145,7 @@ class SessionHandler(dict):
if include_unloggedin:
return listvalues(self)
else:
return [session for session in self.values() if session.logged_in]
return [session for session in list(self.values()) if session.logged_in]
def get_all_sync_data(self):
"""
@ -156,7 +156,7 @@ class SessionHandler(dict):
syncdata (dict): A dict of sync data.
"""
return dict((sessid, sess.get_sync_data()) for sessid, sess in self.items())
return dict((sessid, sess.get_sync_data()) for sessid, sess in list(self.items()))
def clean_senddata(self, session, kwargs):
"""
@ -189,12 +189,12 @@ class SessionHandler(dict):
"Helper function to convert data to AMP-safe (picketable) values"
if isinstance(data, dict):
newdict = {}
for key, part in data.items():
for key, part in list(data.items()):
newdict[key] = _validate(part)
return newdict
elif hasattr(data, "__iter__"):
return [_validate(part) for part in data]
elif isinstance(data, basestring):
elif isinstance(data, str):
# make sure strings are in a valid encoding
try:
data = data and to_str(to_unicode(data), encoding=session.protocol_flags["ENCODING"])
@ -214,12 +214,12 @@ class SessionHandler(dict):
elif hasattr(data, "id") and hasattr(data, "db_date_created") \
and hasattr(data, '__dbclass__'):
# convert database-object to their string representation.
return _validate(unicode(data))
return _validate(str(data))
else:
return data
rkwargs = {}
for key, data in kwargs.iteritems():
for key, data in kwargs.items():
key = _validate(key)
if not data:
if key == "text":
@ -347,12 +347,12 @@ class ServerSessionHandler(SessionHandler):
delayed_import()
global _ServerSession, _AccountDB, _ServerConfig, _ScriptDB
for sess in self.values():
for sess in list(self.values()):
# we delete the old session to make sure to catch eventual
# lingering references.
del sess
for sessid, sessdict in portalsessionsdata.items():
for sessid, sessdict in list(portalsessionsdata.items()):
sess = _ServerSession()
sess.sessionhandler = self
sess.load_sync_data(sessdict)
@ -565,7 +565,7 @@ class ServerSessionHandler(SessionHandler):
"""
uid = curr_session.uid
doublet_sessions = [sess for sess in self.values()
doublet_sessions = [sess for sess in list(self.values())
if sess.logged_in and
sess.uid == uid and
sess != curr_session]
@ -580,7 +580,7 @@ class ServerSessionHandler(SessionHandler):
"""
tcurr = time.time()
reason = _("Idle timeout exceeded, disconnecting.")
for session in (session for session in self.values()
for session in (session for session in list(self.values())
if session.logged_in and _IDLE_TIMEOUT > 0 and
(tcurr - session.cmd_last) > _IDLE_TIMEOUT):
self.disconnect(session, reason=reason)
@ -595,7 +595,7 @@ class ServerSessionHandler(SessionHandler):
naccount (int): Number of connected accounts
"""
return len(set(session.uid for session in self.values() if session.logged_in))
return len(set(session.uid for session in list(self.values()) if session.logged_in))
def all_connected_accounts(self):
"""
@ -606,7 +606,7 @@ class ServerSessionHandler(SessionHandler):
amount of Sessions due to multi-playing).
"""
return list(set(session.account for session in self.values() if session.logged_in and session.account))
return list(set(session.account for session in list(self.values()) if session.logged_in and session.account))
def session_from_sessid(self, sessid):
"""
@ -653,7 +653,7 @@ class ServerSessionHandler(SessionHandler):
"""
uid = account.uid
return [session for session in self.values() if session.logged_in and session.uid == uid]
return [session for session in list(self.values()) if session.logged_in and session.uid == uid]
def sessions_from_puppet(self, puppet):
"""
@ -680,7 +680,7 @@ class ServerSessionHandler(SessionHandler):
csessid (str): The session hash
"""
return [session for session in self.values()
return [session for session in list(self.values())
if session.csessid and session.csessid == csessid]
def announce_all(self, message):
@ -691,7 +691,7 @@ class ServerSessionHandler(SessionHandler):
message (str): Message to send.
"""
for session in self.values():
for session in list(self.values()):
self.data_out(session, text=message)
def data_out(self, session, **kwargs):
@ -754,7 +754,7 @@ class ServerSessionHandler(SessionHandler):
# distribute incoming data to the correct receiving methods.
if session:
input_debug = session.protocol_flags.get("INPUTDEBUG", False)
for cmdname, (cmdargs, cmdkwargs) in kwargs.iteritems():
for cmdname, (cmdargs, cmdkwargs) in kwargs.items():
cname = cmdname.strip().lower()
try:
cmdkwargs.pop("options", None)

View file

@ -11,8 +11,8 @@ application.
a great example/aid on how to do this.)
"""
import urlparse
from urllib import quote as urlquote
import urllib.parse
from urllib.parse import quote as urlquote
from twisted.web import resource, http, server
from twisted.internet import reactor
from twisted.application import internet
@ -117,7 +117,7 @@ class EvenniaReverseProxyResource(ReverseProxyResource):
# RFC 2616 tells us that we can omit the port if it's the default port,
# but we have to provide it otherwise
request.content.seek(0, 0)
qs = urlparse.urlparse(request.uri)[4]
qs = urllib.parse.urlparse(request.uri)[4]
if qs:
rest = self.path + '?' + qs
else: