Ticket #5965: python3_porting1.patch

File python3_porting1.patch, 23.3 KB (added by realcr, 3 years ago)

Python3 porting fixes

  • .gitignore

    diff --git .gitignore .gitignore
    index 7039ee4..afdad62 100644
     
    55_trial_temp*/
    66build/
    77dropin.cache
    8 *.swp
  • deleted file bin/trial3

    diff --git bin/trial3 bin/trial3
    deleted file mode 100755
    index a00652b..0000000
    + -  
    1 #!/usr/bin/env python3.2
    2 # Copyright (c) Twisted Matrix Laboratories.
    3 # See LICENSE for details.
    4 import os, sys
    5 
    6 try:
    7     import _preamble
    8 except ImportError:
    9     sys.exc_clear()
    10 
    11 # begin chdir armor
    12 sys.path[:] = map(os.path.abspath, sys.path)
    13 # end chdir armor
    14 
    15 sys.path.insert(0, os.path.abspath(os.getcwd()))
    16 
    17 from twisted.scripts.trial import run
    18 run()
  • twisted/application/app.py

    diff --git twisted/application/app.py twisted/application/app.py
    index 9384e09..f0545d0 100644
     
    22# Copyright (c) Twisted Matrix Laboratories.
    33# See LICENSE for details.
    44
    5 from __future__ import division, absolute_import
    65import sys, os, pdb, getpass, traceback, signal
    76from operator import attrgetter
    87
    class ProfileRunner(_BasicProfiler): 
    6564        """
    6665        try:
    6766            import profile
    68         except ImportError as e:
     67        except ImportError, e:
    6968            self._reportImportError("profile", e)
    7069
    7170        p = profile.Profile()
    class HotshotRunner(_BasicProfiler): 
    9392        """
    9493        try:
    9594            import hotshot.stats
    96         except (ImportError, SystemExit) as e:
     95        except (ImportError, SystemExit), e:
    9796            # Certain versions of Debian (and Debian derivatives) raise
    9897            # SystemExit when importing hotshot if the "non-free" profiler
    9998            # module is not installed.  Someone eventually recognized this
    class CProfileRunner(_BasicProfiler): 
    134133        """
    135134        try:
    136135            import cProfile, pstats
    137         except ImportError as e:
     136        except ImportError, e:
    138137            self._reportImportError("cProfile", e)
    139138
    140139        p = cProfile.Profile()
    def fixPdb(): 
    264263
    265264
    266265    def help_stop(self):
    267         print("stop - Continue execution, then cleanly shutdown the " + \
    268                 "twisted reactor.")
     266        print """stop - Continue execution, then cleanly shutdown the twisted reactor."""
    269267
    270268
    271269    def set_quit(self):
    def getApplication(config, passphrase): 
    453451        log.msg("Loading %s..." % filename)
    454452        application = service.loadApplication(filename, style, passphrase)
    455453        log.msg("Loaded.")
    456     except Exception as e:
     454    except Exception, e:
    457455        s = "Failed to load application: %s" % e
    458456        if isinstance(e, KeyError) and e.args[0] == "application":
    459457            s += """
    class ReactorSelectionMixin: 
    517515                   "See the list of available reactors with "
    518516                   "--help-reactors" % (shortName,))
    519517            raise usage.UsageError(msg)
    520         except Exception as e:
     518        except Exception, e:
    521519            msg = ("The specified reactor cannot be used, failed with error: "
    522520                   "%s.\nSee the list of available reactors with "
    523521                   "--help-reactors" % (e,))
    class ServerOptions(usage.Options, ReactorSelectionMixin): 
    612610        if self['logger'] is not None:
    613611            try:
    614612                self['logger'] = namedAny(self['logger'])
    615             except Exception as e:
     613            except Exception, e:
    616614                raise usage.UsageError("Logger '%s' could not be imported: %s"
    617615                                       % (self['logger'], e))
    618616
    def run(runApp, ServerOptions): 
    637635    config = ServerOptions()
    638636    try:
    639637        config.parseOptions()
    640     except usage.error as ue:
    641         print(config)
    642         print("%s: %s" % (sys.argv[0], ue))
     638    except usage.error, ue:
     639        print config
     640        print "%s: %s" % (sys.argv[0], ue)
    643641    else:
    644642        runApp(config)
    645643
  • twisted/application/reactors.py

    diff --git twisted/application/reactors.py twisted/application/reactors.py
    index 429f192..cccddd1 100644
     
    66Plugin-based system for enumerating available reactors and installing one of
    77them.
    88"""
    9 from __future__ import division, absolute_import
    10 from zope.interface import Interface, Attribute, implementer
     9
     10from zope.interface import Interface, Attribute, implements
    1111
    1212from twisted.plugin import IPlugin, getPlugins
    1313from twisted.python.reflect import namedAny
    class NoSuchReactor(KeyError): 
    4141    """
    4242
    4343
    44 @implementer(IPlugin, IReactorInstaller)
    4544class Reactor(object):
    4645    """
    4746    @ivar moduleName: The fully-qualified Python name of the module of which
    4847    the install callable is an attribute.
    4948    """
     49    implements(IPlugin, IReactorInstaller)
     50
    5051
    5152    def __init__(self, shortName, moduleName, description):
    5253        self.shortName = shortName
  • twisted/application/service.py

    diff --git twisted/application/service.py twisted/application/service.py
    index 668519e..66fef85 100644
    a sibling). 
    1212
    1313Maintainer: Moshe Zadka
    1414"""
    15 from __future__ import division, absolute_import
    16 from zope.interface import implementer, Interface, Attribute
     15
     16from zope.interface import implements, Interface, Attribute
    1717
    1818from twisted.python.reflect import namedAny
    1919from twisted.python import components
    class IServiceMaker(Interface): 
    5656
    5757
    5858
    59 @implementer(IPlugin, IServiceMaker)
    6059class ServiceMaker(object):
    6160    """
    6261    Utility class to simplify the definition of L{IServiceMaker} plugins.
    6362    """
     63    implements(IPlugin, IServiceMaker)
    6464
    6565    def __init__(self, name, module, description, tapname):
    6666        self.name = name
    class IService(Interface): 
    152152        """
    153153
    154154
    155 @implementer(IService)
    156155class Service:
    157156    """
    158157    Base class for services.
    class Service: 
    162161    as not serializing this book-keeping information.
    163162    """
    164163
     164    implements(IService)
    165165
    166166    running = 0
    167167    name = None
    class IServiceCollection(Interface): 
    254254
    255255
    256256
    257 @implementer(IServiceCollection)
    258257class MultiService(Service):
    259258    """
    260259    Straightforward Service Container.
    class MultiService(Service): 
    265264    will finish.
    266265    """
    267266
     267    implements(IServiceCollection)
     268
    268269    def __init__(self):
    269270        self.services = []
    270271        self.namedServices = {}
    class IProcess(Interface): 
    346347
    347348
    348349
    349 @implementer(IProcess)
    350350class Process:
    351351    """
    352352    Process running parameters.
    class Process: 
    354354    Sets up uid/gid in the constructor, and has a default
    355355    of C{None} as C{processName}.
    356356    """
     357    implements(IProcess)
    357358    processName = None
    358359
    359360    def __init__(self, uid=None, gid=None):
  • twisted/persisted/sob.py

    diff --git twisted/persisted/sob.py twisted/persisted/sob.py
    index 0b72b52..89d9caa 100644
    Save and load Small OBjects to and from files, using various formats. 
    99Maintainer: Moshe Zadka
    1010"""
    1111
    12 from __future__ import division, absolute_import
    13 from twisted.python.compat import _PY3
    1412import os, sys
    1513try:
    1614    import cPickle as pickle
    1715except ImportError:
    1816    import pickle
    19 
    20 if _PY3:
    21     from io import StringIO
    22 else:
    23     try:
    24         import cStringIO as StringIO
    25     except ImportError:
    26         import StringIO
     17try:
     18    import cStringIO as StringIO
     19except ImportError:
     20    import StringIO
    2721from hashlib import md5
    2822from twisted.python import log, runtime
    2923from twisted.persisted import styles
    30 from zope.interface import implementer, Interface
     24from zope.interface import implements, Interface
    3125
    3226# Note:
    3327# These encrypt/decrypt functions only work for data formats
    class IPersistable(Interface): 
    6458        """
    6559
    6660
    67 @implementer(IPersistable)
    6861class Persistent:
    6962
     63    implements(IPersistable)
     64
    7065    style = "pickle"
    7166
    7267    def __init__(self, original, name):
    def loadValueFromFile(filename, variable, passphrase=None): 
    210205    if passphrase:
    211206        data = fileObj.read()
    212207        data = _decrypt(passphrase, data)
    213         exec(data, d, d)
     208        exec data in d, d
    214209    else:
    215         exec(fileObj, d, d)
     210        exec fileObj in d, d
    216211    value = d[variable]
    217212    return value
    218213
  • twisted/persisted/styles.py

    diff --git twisted/persisted/styles.py twisted/persisted/styles.py
    index 8f39fa8..e3ca39b 100644
     
    33# See LICENSE for details.
    44
    55
     6
    67"""
    78Different styles of persisted objects.
    89"""
    910
    10 from __future__ import division, absolute_import
    11 from twisted.python.compat import _PY3
    1211# System Imports
    1312import types
    14 
    15 
    16 if not _PY3:
    17     import copy_reg
    18 else:
    19     import copyreg as copy_reg
     13import copy_reg
    2014import copy
    2115import inspect
    2216import sys
    2317
    24 if _PY3:
    25     from io import StringIO
    26 else:
    27     try:
    28         from cStringIO import StringIO
    29     except ImportError:
    30         from StringIO import StringIO
     18try:
     19    import cStringIO as StringIO
     20except ImportError:
     21    import StringIO
    3122
    3223# Twisted Imports
    3324from twisted.python import log
  • twisted/plugin.py

    diff --git twisted/plugin.py twisted/plugin.py
    index 544dac4..a4f8334 100644
    Plugin system for Twisted. 
    1010@author: Glyph Lefkowitz
    1111"""
    1212
    13 from __future__ import division, absolute_import
    1413import os
    1514import sys
    1615
    def getCache(module): 
    180179        if needsWrite:
    181180            try:
    182181                dropinPath.setContent(pickle.dumps(dropinDotCache))
    183             except OSError as e:
     182            except OSError, e:
    184183                log.msg(
    185184                    format=(
    186185                        "Unable to write to plugin cache %(path)s: error "
  • twisted/python/filepath.py

    diff --git twisted/python/filepath.py twisted/python/filepath.py
    index 71e038a..d3f8b8a 100644
    class FilePath(AbstractFilePath): 
    675675        if platform.isWindows() and path.count(b":"):
    676676            # Catch paths like C:blah that don't have a slash
    677677            raise InsecurePath("%r contains a colon." % (path,))
    678 
    679678        norm = normpath(path)
    680679        if self.sep in norm:
    681680            raise InsecurePath("%r contains one or more directory separators" % (path,))
  • twisted/python/logfile.py

    diff --git twisted/python/logfile.py twisted/python/logfile.py
    index bce4b56..f652271 100644
     
    77A rotating, browsable log file.
    88"""
    99
    10 from __future__ import division, absolute_import
    1110# System Imports
    1211import os, glob, time, stat
    1312
    class BaseLogFile: 
    6766        else:
    6867            if self.defaultMode is not None:
    6968                # Set the lowest permissions
    70                 oldUmask = os.umask(int("777",8))
     69                oldUmask = os.umask(0777)
    7170                try:
    7271                    self._file = file(self.path, "w+", 1)
    7372                finally:
    class LogFile(BaseLogFile): 
    179178        """
    180179        filename = "%s.%d" % (self.path, identifier)
    181180        if not os.path.exists(filename):
    182             raise ValueError("no such logfile exists")
     181            raise ValueError, "no such logfile exists"
    183182        return LogReader(filename)
    184183
    185184    def write(self, data):
    class DailyLogFile(BaseLogFile): 
    267266            return self.getCurrentLog()
    268267        filename = "%s.%s" % (self.path, self.suffix(identifier))
    269268        if not os.path.exists(filename):
    270             raise ValueError("no such logfile exists")
     269            raise ValueError, "no such logfile exists"
    271270        return LogReader(filename)
    272271
    273272    def write(self, data):
  • twisted/python/modules.py

    diff --git twisted/python/modules.py twisted/python/modules.py
    index 6ec09ed..11455be 100644
    the modules outside the standard library's python-files directory:: 
    5353                modinfo.name, modinfo.filePath.path)
    5454"""
    5555
    56 from __future__ import division, absolute_import
    57 from twisted.python.compat import _PY3
    58 
    5956__metaclass__ = type
    6057
    6158# let's try to keep path imports to a minimum...
    import sys 
    6562import zipimport
    6663import inspect
    6764import warnings
    68 from zope.interface import Interface, implementer
     65from zope.interface import Interface, implements
    6966
    7067from twisted.python.components import registerAdapter
    7168from twisted.python.filepath import FilePath, UnlistableError
    class _ModuleIteratorHelper: 
    134131            except UnlistableError:
    135132                continue
    136133
    137             if _PY3:
    138                 # Might be not very efficient, but that's the price of sorting
    139                 # here.
    140                 children = list(children)
    141 
    142134            children.sort()
    143135            for potentialTopLevel in children:
    144136                ext = potentialTopLevel.splitext()[1]
    class IPathImportMapper(Interface): 
    484476        L{ZipPath}, but more might be added later).
    485477        """
    486478
    487 @implementer(IPathImportMapper)
    488479class _DefaultMapImpl:
    489480    """ Wrapper for the default importer, i.e. None.  """
     481    implements(IPathImportMapper)
    490482    def mapPath(self, fsPathString):
    491483        return FilePath(fsPathString)
    492484_theDefaultMapper = _DefaultMapImpl()
    493485
    494 @implementer(IPathImportMapper)
    495486class _ZipMapImpl:
    496487    """ IPathImportMapper implementation for zipimport.ZipImporter.  """
     488    implements(IPathImportMapper)
    497489    def __init__(self, importer):
    498490        self.importer = importer
    499491
  • twisted/python/reflect.py

    diff --git twisted/python/reflect.py twisted/python/reflect.py
    index e8bead0..ac25d47 100644
    Standardized versions of various cool and/or strange things that you can do 
    77with Python's reflection capabilities.
    88"""
    99
    10 from __future__ import division, absolute_import
    1110import sys
    1211import types
    1312import pickle
    import re 
    1615import warnings
    1716from collections import deque
    1817
    19 from twisted.python.compat import _PY3
    2018RegexType = type(re.compile(""))
    2119
    22 if _PY3:
    23     from io import StringIO
    24 else:
    25     try:
    26         from cStringIO import StringIO
    27     except ImportError:
    28         from StringIO import StringIO
    29 
    3020
     21try:
     22    from cStringIO import StringIO
     23except ImportError:
     24    from StringIO import StringIO
    3125
    3226from twisted.python.compat import _PY3
    3327from twisted.python.deprecate import deprecated
    def objgrep(start, goal, eq=isLike, path='', paths=None, seen=None, showUnknowns 
    284278                                   'member_descriptor', 'getset_descriptor')):
    285279        pass
    286280    elif showUnknowns:
    287         print('unknown type', type(start), start)
     281        print 'unknown type', type(start), start
    288282    return paths
    289283
    290284
  • twisted/python/usage.py

    diff --git twisted/python/usage.py twisted/python/usage.py
    index 988f3e4..9280ae2 100644
    U{http://twistedmatrix.com/projects/core/documentation/howto/options.html}, 
    1212or doc/core/howto/options.xhtml in your Twisted directory.
    1313"""
    1414
    15 from __future__ import division, absolute_import
    16 from twisted.python.compat import _PY3
    17 
    1815# System Imports
    1916import os
    2017import sys
    class CoerceParameter(object): 
    5552                             % (parameterName,))
    5653        try:
    5754            value = self.coerce(value)
    58         except ValueError as e:
     55        except ValueError, e:
    5956            raise UsageError("Parameter type enforcement failed: %s" % (e,))
    6057
    6158        self.options.opts[parameterName] = value
    class Options(dict): 
    191188        as dictionary keys.  This is an internal feature used to implement
    192189        the parser.  Do not rely on it in application code.
    193190        """
    194         if _PY3:
    195             # In Python3 integer has no size limit.
    196             return int(id(self))
    197         else:
    198             return int(id(self) % sys.maxint)
     191        return int(id(self) % sys.maxint)
    199192
    200193    def opt_help(self):
    201194        """
    202195        Display this help and exit.
    203196        """
    204         print(self.__str__())
     197        print self.__str__()
    205198        sys.exit(0)
    206199
    207200    def opt_version(self):
    class Options(dict): 
    209202        Display Twisted version and exit.
    210203        """
    211204        from twisted import copyright
    212         print("Twisted version:", copyright.version)
     205        print "Twisted version:", copyright.version
    213206        sys.exit(0)
    214207
    215208    #opt_h = opt_help # this conflicted with existing 'host' options.
    class Options(dict): 
    239232        try:
    240233            opts, args = getopt.getopt(options,
    241234                                       self.shortOpt, self.longOpt)
    242         except getopt.error as e:
     235        except getopt.error, e:
    243236            raise UsageError(str(e))
    244237
    245238        for opt, arg in opts:
    class Options(dict): 
    439432                reverse_dct[method] = []
    440433            reverse_dct[method].append(name.replace('_', '-'))
    441434
    442         if _PY3:
    443             def sort_by_length(lst):
    444                 """
    445                 Sort list elements by their length.
    446                 """
    447                 # Here we use a key function instead of a compare function.
    448                 KeyLength = lambda a:len(a)
    449                 lst.sort(key=KeyLength)
    450         else:
    451             def sort_by_length(lst):
    452                 # Old fashioned compare function here:
    453                 cmpLength = lambda a, b: cmp(len(a), len(b))
    454                 lst.sort(cmpLength)
     435        cmpLength = lambda a, b: cmp(len(a), len(b))
    455436
    456437        for method, names in reverse_dct.items():
    457438            if len(names) < 2:
    458439                continue
    459440            names_ = names[:]
    460             sort_by_length(names_)
     441            names_.sort(cmpLength)
    461442            longest = names_.pop()
    462443            for name in names_:
    463444                synonyms[name] = longest
    def docMakeChunks(optList, width=80): 
    969950
    970951
    971952def flagFunction(method, name=None):
    972     if _PY3:
    973         reqArgs = method.__func__.__code__.co_argcount
    974     else:
    975         reqArgs = method.im_func.func_code.co_argcount
     953    reqArgs = method.im_func.func_code.co_argcount
    976954    if reqArgs > 2:
    977955        raise UsageError('Invalid Option function for %s' %
    978956                         (name or method.func_name))
  • twisted/python/util.py

    diff --git twisted/python/util.py twisted/python/util.py
    index 97e33a1..3b3a699 100644
    __all__ = [ 
    10781078    ]
    10791079
    10801080
    1081 #   if _PY3:
    1082 #       __all3__ = ["FancyEqMixin", "setIDFunction", "unsignedID", "untilConcludes",
    1083 #                   "runWithWarningsSuppressed", "FancyStrMixin", "nameToLabel",
    1084 #                   "InsensitiveDict","spewer"]
    1085 #       for name in __all__[:]:
    1086 #           if name not in __all3__:
    1087 #               __all__.remove(name)
    1088 #               del globals()[name]
    1089 #       del name, __all3__
     1081if _PY3:
     1082    __all3__ = ["FancyEqMixin", "setIDFunction", "unsignedID", "untilConcludes",
     1083                "runWithWarningsSuppressed", "FancyStrMixin", "nameToLabel",
     1084                "InsensitiveDict"]
     1085    for name in __all__[:]:
     1086        if name not in __all3__:
     1087            __all__.remove(name)
     1088            del globals()[name]
     1089    del name, __all3__
  • twisted/python/zippath.py

    diff --git twisted/python/zippath.py twisted/python/zippath.py
    index 5113e90..a82f253 100644
    This module contains implementations of IFilePath for zip files. 
    88See the constructor for ZipArchive for use.
    99"""
    1010
    11 from __future__ import division, absolute_import
    1211__metaclass__ = type
    1312
    1413import os
    else: 
    2827
    2928from twisted.python.filepath import IFilePath, FilePath, AbstractFilePath
    3029
    31 from zope.interface import implementer
     30from zope.interface import implements
    3231
    3332# using FilePath here exclusively rather than os to make sure that we don't do
    3433# anything OS-path-specific here.
    ZIP_PATH_SEP = '/' # In zipfiles, "/" is universally used as the 
    3736                                # path separator, regardless of platform.
    3837
    3938
    40 @implementer(IFilePath)
    4139class ZipPath(AbstractFilePath):
    4240    """
    4341    I represent a file or directory contained within a zip file.
    4442    """
    4543
     44    implements(IFilePath)
     45
    4646    sep = ZIP_PATH_SEP
    4747
    4848    def __init__(self, archive, pathInArchive):
  • twisted/scripts/trial.py

    diff --git twisted/scripts/trial.py twisted/scripts/trial.py
    index a60d316..7cdaa3c 100644
     
    44# See LICENSE for details.
    55
    66
    7 from __future__ import print_function,division,absolute_import
     7from __future__ import print_function
    88import gc
    99import inspect
    1010import os
    def run(): 
    599599    config = Options()
    600600    try:
    601601        config.parseOptions()
    602     except usage.error as ue:
    603         raise SystemExit("%s: %s" % (sys.argv[0], ue))
     602    except usage.error, ue:
     603        raise SystemExit, "%s: %s" % (sys.argv[0], ue)
    604604    _initialDebugSetup(config)
    605605
    606606    try:
  • twisted/trial/_asyncrunner.py

    diff --git twisted/trial/_asyncrunner.py twisted/trial/_asyncrunner.py
    index 0a34a7f..a46d185 100644
     
    66Infrastructure for test running and suites.
    77"""
    88
    9 from __future__ import division, absolute_import
    10 
    119import doctest
    1210import gc
    1311
    from twisted.trial._synctest import _logObserver 
    1816
    1917pyunit = __import__('unittest')
    2018
    21 from zope.interface import implementer
     19from zope.interface import implements
    2220
    2321
    2422
    class TestSuite(pyunit.TestSuite): 
    4038
    4139
    4240
    43 @implementer(itrial.ITestCase)
    4441class TestDecorator(components.proxyForInterface(itrial.ITestCase,
    4542                                                 "_originalTest")):
    4643    """
    class TestDecorator(components.proxyForInterface(itrial.ITestCase, 
    5047    @type _originalTest: A provider of L{itrial.ITestCase}
    5148    """
    5249
     50    implements(itrial.ITestCase)
     51
     52
    5353    def __call__(self, result):
    5454        """
    5555        Run the unit test.
  • twisted/trial/runner.py

    diff --git twisted/trial/runner.py twisted/trial/runner.py
    index 7e1834e..4275c24 100644
    A miscellany of code used to run Trial tests. 
    88Maintainer: Jonathan Lange
    99"""
    1010
    11 from __future__ import division, absolute_import
    12 
    1311__all__ = [
    1412    'TestSuite',
    1513
    from twisted.trial.reporter import _ExitWrapper, UncleanWarningsReporterWrapper 
    3533# These are imported so that they remain in the public API for t.trial.runner
    3634from twisted.trial.unittest import TestSuite
    3735
    38 from zope.interface import implementer
     36from zope.interface import implements
    3937
    4038pyunit = __import__('unittest')
    4139
    def isTestCase(obj): 
    254252
    255253
    256254
    257 @implementer(ITestCase)
    258255class TestHolder(object):
    259256    """
    260257    Placeholder for a L{TestCase} inside a reporter. As far as a L{TestResult}
    261258    is concerned, this looks exactly like a unit test.
    262259    """
    263260
     261    implements(ITestCase)
    264262
    265263    failureException = None
    266264
  • twisted/trial/unittest.py

    diff --git twisted/trial/unittest.py twisted/trial/unittest.py
    index 8d33af3..8f07556 100644
    from twisted.trial._asynctest import TestCase 
    1616
    1717from twisted.python.compat import _PY3
    1818
    19 # There was some check here, and the following was executed only on versions
    20 # lower on Python3. I removed it:
    21 from twisted.trial._asyncrunner import (
    22     TestSuite, TestDecorator, decorate)
    23 from twisted.trial._asyncrunner import (
    24     _ForceGarbageCollectionDecorator, _iterateTests, _clearSuite)
     19if not _PY3:
     20    from twisted.trial._asyncrunner import (
     21        TestSuite, TestDecorator, decorate)
     22    from twisted.trial._asyncrunner import (
     23        _ForceGarbageCollectionDecorator, _iterateTests, _clearSuite)
    2524
    2625# Further obscure the origins of these objects, to reduce surprise (and this is
    2726# what the values were before code got shuffled around between files, but was