Commits

Berker Peksag  committed 240083e Draft

Merge Python 3 support.

  • Participants
  • Parent commits 07ea320

Comments (0)

Files changed (27)

File docs/news.txt

 
 .. contents::
 
+hg tip
+------
+
+* six module is now required.
+
+* Drop support of Python 2.5 and older
+
 1.7.5
 -----
 

File paste/script/appinstall.py

 Provides the two commands for preparing an application:
 ``prepare-app`` and ``setup-app``
 """
+from __future__ import print_function
 
 import os
 import sys
-if sys.version_info < (2, 4):
-    from paste.script.util import string24 as string
-else:
+import six
+from six.moves import filter
     import string
 import new
-from cStringIO import StringIO
+from six.moves.cStringIO import StringIO
 from paste.script.command import Command, BadCommand, run as run_command
 import paste.script.templates
 from paste.script import copydir
 import pkg_resources
 Cheetah = None
-from ConfigParser import ConfigParser
+from six.moves.configparser import ConfigParser
 from paste.util import import_string
 from paste.deploy import appconfig
 from paste.script.util import uuid
             if args[0] == '--sysconfig':
                 args.pop(0)
                 if not args:
-                    raise BadCommand, (
+                    raise BadCommand(
                         "You gave --sysconfig as the last argument without "
                         "a value")
                 self.sysconfigs.insert(0, (True, args.pop(0)))
             if name.endswith('.py'):
                 if not os.path.exists(name):
                     if explicit:
-                        raise BadCommand, (
+                        raise BadCommand(
                             "sysconfig file %s does not exist"
                             % name)
                     else:
                         continue
                 globs = {}
-                execfile(name, globs)
+                six.exec_(compile(open(name).read(), name, 'exec'), globs)
                 mod = new.module('__sysconfig_%i__' % index)
                 for name, value in globs.items():
                     setattr(mod, name, value)
             else:
                 try:
                     mod = import_string.simple_import(name)
-                except ImportError, e:
+                except ImportError as e:
                     if explicit:
                         raise
                     else:
         """
         val = self.get_sysconfig_option(name)
         if val is None:
-            raise NameError, (
+            raise NameError(
                 "Method %s not found in any sysconfig module" % name)
         return val(*args, **kw)
 
         try:
             dist = pkg_resources.get_distribution(req)
             if self.verbose:
-                print 'Distribution already installed:'
-                print ' ', dist, 'from', dist.location
+                print('Distribution already installed:')
+                print(' ', dist, 'from', dist.location)
             return dist
         except pkg_resources.DistributionNotFound:
             if self.options.no_install:
-                print "Because --no-install was given, we won't try to install the package %s" % req
+                print("Because --no-install was given, we won't try to install the package %s" % req)
                 raise
             options = ['-v', '-m']
             for op in self.options.easy_install_op or []:
             if self.simulate:
                 raise BadCommand(
                     "Must install %s, but in simulation mode" % req)
-            print "Must install %s" % req
+            print("Must install %s" % req)
             from setuptools.command import easy_install
             from setuptools import setup
             setup(script_args=['-q', 'easy_install']
         if self.verbose > 1:
             print_vars = self.vars.items()
             print_vars.sort()
-            print 'Variables for installation:'
+            print('Variables for installation:')
             for name, value in print_vars:
-                print '  %s: %r' % (name, value)
+                print('  %s: %r' % (name, value))
         self.installer.write_config(self, self.config_file, self.vars)
         edit_success = True
         if self.options.edit:
         setup_config = setup_configs[0]
         if self.options.run_setup:
             if not edit_success:
-                print 'Config-file editing was not successful.'
+                print('Config-file editing was not successful.')
                 if self.ask('Run setup-app anyway?', default=False):
                     self.run_setup(setup_config)
             else:
                 self.run_setup(setup_config)
         else:
             filenames = self.installer.editable_config_files(self.config_file)
-            assert not isinstance(filenames, basestring), (
+            assert not isinstance(filenames, six.string_types), (
                 "editable_config_files returned a string, not a list")
             if not filenames and filenames is not None:
-                print 'No config files need editing'
+                print('No config files need editing')
             else:
-                print 'Now you should edit the config files'
+                print('Now you should edit the config files')
                 if filenames:
                     for fn in filenames:
-                        print '  %s' % fn
+                        print('  %s' % fn)
 
     def show_info(self):
         text = self.installer.description(None)
-        print text
+        print(text)
 
     def check_config_file(self):
         if self.installer.expect_config_directory is None:
     def run_editor(self):
         filenames = self.installer.editable_config_files(self.config_file)
         if filenames is None:
-            print 'Warning: the config file is not known (--edit ignored)'
+            print('Warning: the config file is not known (--edit ignored)')
             return False
         if not filenames:
-            print 'Warning: no config files need editing (--edit ignored)'
+            print('Warning: no config files need editing (--edit ignored)')
             return True
         if len(filenames) > 1:
-            print 'Warning: there is more than one editable config file (--edit ignored)'
+            print('Warning: there is more than one editable config file (--edit ignored)')
             return False
         if not os.environ.get('EDITOR'):
-            print 'Error: you must set $EDITOR if using --edit'
+            print('Error: you must set $EDITOR if using --edit')
             return False
         if self.verbose:
-            print '%s %s' % (os.environ['EDITOR'], filenames[0])
+            print('%s %s' % (os.environ['EDITOR'], filenames[0]))
         retval = os.system('$EDITOR %s' % filenames[0])
         if retval:
-            print 'Warning: editor %s returned with error code %i' % (
-                os.environ['EDITOR'], retval)
+            print('Warning: editor %s returned with error code %i' % (
+                os.environ['EDITOR'], retval))
             return False
         return True
         
         meta_name = 'paste_deploy_config.ini_tmpl'
         if not self.dist.has_metadata(meta_name):
             if command.verbose:
-                print 'No %s found' % meta_name
+                print('No %s found' % meta_name)
             return self.simple_config(vars)
         return self.template_renderer(
             self.dist.get_metadata(meta_name), vars, filename=meta_name)
             for line in self.dist.get_metadata_lines('top_level.txt')
             if line.strip() and not line.strip().startswith('#')]
         if not modules:
-            print 'No modules are listed in top_level.txt'
-            print 'Try running python setup.py egg_info to regenerate that file'
+            print('No modules are listed in top_level.txt')
+            print('Try running python setup.py egg_info to regenerate that file')
         for mod_name in modules:
             mod_name = mod_name + '.websetup'
             mod = import_string.try_import_module(mod_name)
                 continue
             if hasattr(mod, 'setup_app'):
                 if command.verbose:
-                    print 'Running setup_app() from %s' % mod_name
+                    print('Running setup_app() from %s' % mod_name)
                 self._call_setup_app(
                     mod.setup_app, command, filename, section, vars)
             elif hasattr(mod, 'setup_config'):
                 if command.verbose:
-                    print 'Running setup_config() from %s' % mod_name
+                    print('Running setup_config() from %s' % mod_name)
                 mod.setup_config(command, filename, section, vars)
             else:
-                print 'No setup_app() or setup_config() function in %s (%s)' % (
-                    mod.__name__, mod.__file__)
+                print('No setup_app() or setup_config() function in %s (%s)' % (
+                    mod.__name__, mod.__file__))
 
     def _call_setup_app(self, func, command, filename, section, vars):
         filename = os.path.abspath(filename)

File paste/script/cgi_server.py

 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 import os
+import six
 import sys
 
 ## FIXME: this should be deprecated in favor of wsgiref
             try:
                 if headers_sent:
                     # Re-raise original exception if headers sent
-                    raise exc_info[0], exc_info[1], exc_info[2]
+                    six.reraise(*exc_info)
             finally:
                 exc_info = None     # avoid dangling circular ref
         elif headers_set:

File paste/script/checkperms.py

     Examples::
 
       >>> print oct(read_perm_spec('rw-r--r--'))
-      0644
+      0o644
       >>> print oct(read_perm_spec('rw-rwsr--'))
-      02664
+      0o2664
       >>> print oct(read_perm_spec('r-xr--r--'))
-      0544
+      0o544
       >>> print oct(read_perm_spec('r--------'))
-      0400
+      0o400
     """
     total_mask = 0
     # suid/sgid modes give this mask in user, group, other mode:
-    set_bits = (04000, 02000, 0)
+    set_bits = (0o4000, 0o2000, 0)
     pieces = (spec[0:3], spec[3:6], spec[6:9])
     for i, (mode, set_bit) in enumerate(zip(pieces, set_bits)):
         mask = 0
         if read == 'r':
             mask = mask | 4
         elif read != '-':
-            raise ValueError, (
+            raise ValueError(
                 "Character %r unexpected (should be '-' or 'r')"
                 % read)
         if write == 'w':
             mask = mask | 2
         elif write != '-':
-            raise ValueError, (
+            raise ValueError(
                 "Character %r unexpected (should be '-' or 'w')"
                 % write)
         if exe == 'x':
             mask = mask | 1
         elif exe not in ('s', '-'):
-            raise ValueError, (
+            raise ValueError(
                 "Character %r unexpected (should be '-', 'x', or 's')"
                 % exe)
         if exe == 's' and i == 2:
-            raise ValueError, (
-                "The 'other' executable setting cannot be suid/sgid ('s')")
+            raise ValueError((
+                "The 'other' executable setting cannot be suid/sgid ('s')"))
         mask = mask << ((2-i)*3)
         if exe == 's':
             mask = mask | set_bit
     return total_mask
 
 modes = [
-    (04000, 'setuid bit',
+    (0o4000, 'setuid bit',
      'setuid bit: make contents owned by directory owner'),
-    (02000, 'setgid bit',
+    (0o2000, 'setgid bit',
      'setgid bit: make contents inherit permissions from directory'),
-    (01000, 'sticky bit',
+    (0o1000, 'sticky bit',
      'sticky bit: append-only directory'),
-    (00400, 'read by owner', 'read by owner'),
-    (00200, 'write by owner', 'write by owner'),
-    (00100, 'execute by owner', 'owner can search directory'),
-    (00040, 'allow read by group members',
+    (0o0400, 'read by owner', 'read by owner'),
+    (0o0200, 'write by owner', 'write by owner'),
+    (0o0100, 'execute by owner', 'owner can search directory'),
+    (0o0040, 'allow read by group members',
      'allow read by group members',),
-    (00020, 'allow write by group members',
+    (0o0020, 'allow write by group members',
      'allow write by group members'),
-    (00010, 'execute by group members',
+    (0o0010, 'execute by group members',
      'group members can search directory'),
-    (00004, 'read by others', 'read by others'),
-    (00002, 'write by others', 'write by others'),
-    (00001, 'execution by others', 'others can search directory'),
+    (0o0004, 'read by others', 'read by others'),
+    (0o0002, 'write by others', 'write by others'),
+    (0o0001, 'execution by others', 'others can search directory'),
     ]
 
-exe_bits = [0100, 0010, 0001]
-exe_mask = 0111
-full_mask = 07777
+exe_bits = [0o100, 0o010, 0o001]
+exe_mask = 0o111
+full_mask = 0o7777
 
 def mode_diff(filename, mode, **kw):
     """
 
     Examples::
 
-      >>> print oct(calc_set_mode(0775, 0644))
-      0755
-      >>> print oct(calc_set_mode(0775, 0744))
-      0744
-      >>> print oct(calc_set_mode(010600, 0644))
-      010644
-      >>> print oct(calc_set_mode(0775, 0644, False))
-      0644
+      >>> print oct(calc_set_mode(0o775, 0o644))
+      0o755
+      >>> print oct(calc_set_mode(0o775, 0o744))
+      0o744
+      >>> print oct(calc_set_mode(0o10600, 0o644))
+      0o10644
+      >>> print oct(calc_set_mode(0o775, 0o644, False))
+      0o644
     """
     for exe_bit in exe_bits:
         if mode & exe_bit:
             os.symlink(path, self.dest)
         else:
             # @@: This should correct the symlink or something:
-            print 'Not symlinking %s' % path
+            print('Not symlinking %s' % path)
 
 class _Permission(_Rule):
 

File paste/script/cherrypy_server.py

 try:
     from cherrypy import wsgiserver
 except ImportError:
-    print '=' * 60
-    print '== You must install CherryPy (pip install cherrypy) to use the egg:PasteScript#cherrypy server'
-    print '=' * 60
+    print('=' * 60)
+    print('== You must install CherryPy (pip install cherrypy) to use the egg:PasteScript#cherrypy server')
+    print('=' * 60)
     raise
 
 try:
     try:
         protocol = is_ssl and 'https' or 'http'
         if host == '0.0.0.0':
-            print 'serving on 0.0.0.0:%s view at %s://127.0.0.1:%s' % \
-                (port, protocol, port)
+            print('serving on 0.0.0.0:%s view at %s://127.0.0.1:%s' % \
+                (port, protocol, port))
         else:
-            print "serving on %s://%s:%s" % (protocol, host, port)
+            print("serving on %s://%s:%s" % (protocol, host, port))
         server.start()
     except (KeyboardInterrupt, SystemExit):
         server.stop()

File paste/script/command.py

 import pkg_resources
 import sys
 import optparse
-import bool_optparse
+from . import bool_optparse
 import os
 import re
 import textwrap
-import pluginlib
-import ConfigParser
+from . import pluginlib
+from six.moves import configparser
 import getpass
+from six.moves import input
 try:
     import subprocess
 except ImportError:
     if options.do_help:
         args = ['help'] + args
     if not args:
-        print 'Usage: %s COMMAND' % sys.argv[0]
+        print('Usage: %s COMMAND' % sys.argv[0])
         args = ['help']
     command_name = args[0]
     if command_name not in commands:
 
 def parse_exe_file(config):
     import shlex
-    p = ConfigParser.RawConfigParser()
+    p = configparser.RawConfigParser()
     p.read([config])
     command_name = 'exe'
     options = []
     try:
         runner = command(command_name)
         exit_code = runner.run(args)
-    except BadCommand, e:
-        print e.message
+    except BadCommand as e:
+        print(e.message)
         exit_code = e.exit_code
     sys.exit(exit_code)
 
         else:
             prompt += ' [y/N]? '
         while 1:
-            response = raw_input(prompt).strip().lower()
+            response = input(prompt).strip().lower()
             if not response:
                 if default in ('careful', 'none'):
-                    print 'Please enter yes or no'
+                    print('Please enter yes or no')
                     continue
                 return default
             if default == 'careful':
                 if response in ('yes', 'no'):
                     return response == 'yes'
-                print 'Please enter "yes" or "no"'
+                print('Please enter "yes" or "no"')
                 continue
             if response[0].lower() in ('y', 'n'):
                 return response[0].lower() == 'y'
-            print 'Y or N please'
+            print('Y or N please')
 
     def challenge(self, prompt, default=NoDefault, should_echo=True):
         """
         if not os.path.exists(dir):
             self.ensure_dir(os.path.dirname(dir))
             if self.verbose:
-                print 'Creating %s' % self.shorten(dir)
+                print('Creating %s' % self.shorten(dir))
             if not self.simulate:
                 os.mkdir(dir)
             if (svn_add and
                 self.svn_command('add', dir)
         else:
             if self.verbose > 1:
-                print "Directory already exists: %s" % self.shorten(dir)
+                print("Directory already exists: %s" % self.shorten(dir))
 
     def ensure_file(self, filename, content, svn_add=True):
         """
         self.ensure_dir(os.path.dirname(filename), svn_add=svn_add)
         if not os.path.exists(filename):
             if self.verbose:
-                print 'Creating %s' % filename
+                print('Creating %s' % filename)
             if not self.simulate:
                 f = open(filename, 'wb')
                 f.write(content)
         f.close()
         if content == old_content:
             if self.verbose > 1:
-                print 'File %s matches expected content' % filename
+                print('File %s matches expected content' % filename)
             return
         if not self.options.overwrite:
-            print 'Warning: file %s does not match expected content' % filename
+            print('Warning: file %s does not match expected content' % filename)
             if difflib is None:
                 import difflib
             diff = difflib.context_diff(
                 old_content.splitlines(),
                 'expected ' + filename,
                 filename)
-            print '\n'.join(diff)
+            print('\n'.join(diff))
             if self.interactive:
                 while 1:
-                    s = raw_input(
+                    s = input(
                         'Overwrite file with new content? [y/N] ').strip().lower()
                     if not s:
                         s = 'n'
                         break
                     if s.startswith('n'):
                         return
-                    print 'Unknown response; Y or N please'
+                    print('Unknown response; Y or N please')
             else:
                 return
                     
         if self.verbose:
-            print 'Overwriting %s with new content' % filename
+            print('Overwriting %s with new content' % filename)
         if not self.simulate:
             f = open(filename, 'wb')
             f.write(content)
             # If we are doing a simulation, it's expected that some
             # files won't exist...
             if self.verbose:
-                print 'Would (if not simulating) insert text into %s' % (
-                    self.shorten(filename))
+                print('Would (if not simulating) insert text into %s' % (
+                    self.shorten(filename)))
             return
                 
         f = open(filename)
                 if (lines[i:] and len(lines[i:]) > 1 and
                     ''.join(lines[i+1:]).strip().startswith(text.strip())):
                     # Already have it!
-                    print 'Warning: line already found in %s (not inserting' % filename
-                    print '  %s' % lines[i]
+                    print('Warning: line already found in %s (not inserting' % filename)
+                    print('  %s' % lines[i])
                     return
                 
                 if indent:
                 "Marker '-*- %s -*-' not found in %s"
                 % (marker_name, filename))
             if 1 or self.simulate: # @@: being permissive right now
-                print 'Warning: %s' % errstr
+                print('Warning: %s' % errstr)
             else:
                 raise ValueError(errstr)
         if self.verbose:
-            print 'Updating %s' % self.shorten(filename)
+            print('Updating %s' % self.shorten(filename))
         if not self.simulate:
             f = open(filename, 'w')
             f.write(''.join(lines))
                                     cwd=cwd,
                                     stderr=stderr_pipe,
                                     stdout=subprocess.PIPE)
-        except OSError, e:
+        except OSError as e:
             if e.errno != 2:
                 # File not found
                 raise
                 "The expected executable %s was not found (%s)"
                 % (cmd, e))
         if self.verbose:
-            print 'Running %s %s' % (cmd, ' '.join(args))
+            print('Running %s %s' % (cmd, ' '.join(args)))
         if simulate:
             return None
         stdout, stderr = proc.communicate()
         if proc.returncode and not expect_returncode:
             if not self.verbose:
-                print 'Running %s %s' % (cmd, ' '.join(args))
-            print 'Error (exit code: %s)' % proc.returncode
+                print('Running %s %s' % (cmd, ' '.join(args)))
+            print('Error (exit code: %s)' % proc.returncode)
             if stderr:
-                print stderr
+                print(stderr)
             raise OSError("Error executing command %s" % cmd)
         if self.verbose > 2:
             if stderr:
-                print 'Command error output:'
-                print stderr
+                print('Command error output:')
+                print(stderr)
             if stdout:
-                print 'Command output:'
-                print stdout
+                print('Command output:')
+                print(stdout)
         elif proc.returncode and warn_returncode:
-            print 'Warning: command failed (%s %s)' % (cmd, ' '.join(args))
-            print 'Exited with code %s' % proc.returncode
+            print('Warning: command failed (%s %s)' % (cmd, ' '.join(args)))
+            print('Exited with code %s' % proc.returncode)
         return stdout
 
     def quote_first_command_arg(self, arg):
         """
         try:
             return self.run_command('svn', *args, **kw)
-        except OSError, e:
+        except OSError as e:
             if not self._svn_failed:
-                print 'Unable to run svn command (%s); proceeding anyway' % e
+                print('Unable to run svn command (%s); proceeding anyway' % e)
                 self._svn_failed = True
 
     def write_file(self, filename, content, source=None,
             f.close()
             if content == old_content:
                 if self.verbose:
-                    print 'File %s exists with same content' % (
-                        self.shorten(filename))
+                    print('File %s exists with same content' % (
+                        self.shorten(filename)))
                 return
             if (not self.simulate and self.options.interactive):
                 if not self.ask('Overwrite file %s?' % filename):
                     return
         if self.verbose > 1 and source:
-            print 'Writing %s from %s' % (self.shorten(filename),
-                                          self.shorten(source))
+            print('Writing %s from %s' % (self.shorten(filename),
+                                          self.shorten(source)))
         elif self.verbose:
-            print 'Writing %s' % self.shorten(filename)
+            print('Writing %s' % self.shorten(filename))
         if not self.simulate:
             already_existed = os.path.exists(filename)
             if binary:
         Given a configuration filename, this will return a map of values.
         """
         result = {}
-        p = ConfigParser.RawConfigParser()
+        p = configparser.RawConfigParser()
         p.read([config])
         if p.has_section(section):
             for key, value in p.items(section):
         """
         modified = False
 
-        p = ConfigParser.RawConfigParser()
+        p = configparser.RawConfigParser()
         if not os.path.exists(config):
             f = open(config, 'w')
             f.write('')
         ConfigParser defaults are specified for the special ``__file__``
         and ``here`` variables, similar to PasteDeploy config loading.
         """
-        parser = ConfigParser.ConfigParser()
+        parser = configparser.ConfigParser()
         parser.read([config_file])
         if parser.has_section('loggers'):
             config_file = os.path.abspath(config_file)
         #for name, value in os.environ.items():
         #    print '%s: %s' % (name, value)
         #print sys.argv
-        print ('Command %r not known (you may need to run setup.py egg_info)'
-               % self.command_name)
+        print(('Command %r not known (you may need to run setup.py egg_info)'
+               % self.command_name))
         commands = get_commands().items()
         commands.sort()
         if not commands:
-            print 'No commands registered.'
-            print 'Have you installed Paste Script?'
-            print '(try running python setup.py develop)'
+            print('No commands registered.')
+            print('Have you installed Paste Script?')
+            print('(try running python setup.py develop)')
             return 2
-        print 'Known commands:'
+        print('Known commands:')
         longest = max([len(n) for n, c in commands])
         for name, command in commands:
-            print '  %s  %s' % (self.pad(name, length=longest),
-                                command.load().summary)
+            print('  %s  %s' % (self.pad(name, length=longest),
+                                command.load().summary))
         return 2
 
 def popdefault(dict, name, default=None):

File paste/script/copydir.py

 import os
 import pkg_resources
 import sys
-if sys.version_info < (2, 4):
-    from paste.script.util import string24 as string
-else:
+from six.moves import input
+from six.moves.urllib.parse import quote
     import string
 import cgi
-import urllib
+
 import re
 Cheetah = None
 try:
     pad = ' '*(indent*2)
     if not os.path.exists(dest):
         if verbosity >= 1:
-            print '%sCreating %s/' % (pad, dest)
+            print('%sCreating %s/' % (pad, dest))
         if not simulate:
             svn_makedirs(dest, svn_add=svn_add, verbosity=verbosity,
                          pad=pad)
     elif verbosity >= 2:
-        print '%sDirectory %s exists' % (pad, dest)
+        print('%sDirectory %s exists' % (pad, dest))
     for name in names:
         if use_pkg_resources:
             full = '/'.join([source[1], name])
         if reason:
             if verbosity >= 2:
                 reason = pad + reason % {'filename': full}
-                print reason
+                print(reason)
             continue
         if sub_vars:
             dest_full = os.path.join(dest, substitute_filename(name, vars))
             sub_file = sub_vars
         if use_pkg_resources and pkg_resources.resource_isdir(source[0], full):
             if verbosity:
-                print '%sRecursing into %s' % (pad, os.path.basename(full))
+                print('%sRecursing into %s' % (pad, os.path.basename(full)))
             copy_dir((source[0], full), dest_full, vars, verbosity, simulate,
                      indent=indent+1, use_cheetah=use_cheetah,
                      sub_vars=sub_vars, interactive=interactive,
             continue
         elif not use_pkg_resources and os.path.isdir(full):
             if verbosity:
-                print '%sRecursing into %s' % (pad, os.path.basename(full))
+                print('%sRecursing into %s' % (pad, os.path.basename(full)))
             copy_dir(full, dest_full, vars, verbosity, simulate,
                      indent=indent+1, use_cheetah=use_cheetah,
                      sub_vars=sub_vars, interactive=interactive,
             f.close()
             if old_content == content:
                 if verbosity:
-                    print '%s%s already exists (same content)' % (pad, dest_full)
+                    print('%s%s already exists (same content)' % (pad, dest_full))
                 continue
             if interactive:
                 if not query_interactive(
             elif not overwrite:
                 continue
         if verbosity and use_pkg_resources:
-            print '%sCopying %s to %s' % (pad, full, dest_full)
+            print('%sCopying %s to %s' % (pad, full, dest_full))
         elif verbosity:
-            print '%sCopying %s to %s' % (pad, os.path.basename(full), dest_full)
+            print('%sCopying %s to %s' % (pad, os.path.basename(full), dest_full))
         if not simulate:
             f = open(dest_full, 'wb')
             f.write(content)
         if svn_add and not already_exists:
             if os.system('svn info %r >/dev/null 2>&1' % os.path.dirname(os.path.abspath(dest_full))) > 0:
                 if verbosity > 1:
-                    print '%sNot part of a svn working copy; cannot add file' % pad
+                    print('%sNot part of a svn working copy; cannot add file' % pad)
             else:
                 cmd = ['svn', 'add', dest_full]
                 if verbosity > 1:
-                    print '%sRunning: %s' % (pad, ' '.join(cmd))
+                    print('%sRunning: %s' % (pad, ' '.join(cmd)))
                 if not simulate:
                     # @@: Should
                     if subprocess is None:
                     proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
                     stdout, stderr = proc.communicate()
                     if verbosity > 1 and stdout:
-                        print 'Script output:'
-                        print stdout
+                        print('Script output:')
+                        print(stdout)
         elif svn_add and already_exists and verbosity > 1:
-            print '%sFile already exists (not doing svn add)' % pad
+            print('%sFile already exists (not doing svn add)' % pad)
 
 def should_skip_file(name):
     """
         msg = '; %i lines removed' % (removed-added)
     else:
         msg = ''
-    print 'Replace %i bytes with %i bytes (%i/%i lines changed%s)' % (
+    print('Replace %i bytes with %i bytes (%i/%i lines changed%s)' % (
         len(dest_content), len(src_content),
-        removed, len(dest_content.splitlines()), msg)
+        removed, len(dest_content.splitlines()), msg))
     prompt = 'Overwrite %s [y/n/d/B/?] ' % dest_fn
     while 1:
         if all_answer is None:
-            response = raw_input(prompt).strip().lower()
+            response = input(prompt).strip().lower()
         else:
             response = all_answer
         if not response or response[0] == 'b':
             while os.path.exists(new_dest_fn):
                 n += 1
                 new_dest_fn = dest_fn + '.bak' + str(n)
-            print 'Backing up %s to %s' % (dest_fn, new_dest_fn)
+            print('Backing up %s to %s' % (dest_fn, new_dest_fn))
             if not simulate:
                 shutil.copyfile(dest_fn, new_dest_fn)
             return True
         elif response.startswith('all '):
             rest = response[4:].strip()
             if not rest or rest[0] not in ('y', 'n', 'b'):
-                print query_usage
+                print(query_usage)
                 continue
             response = all_answer = rest[0]
         if response[0] == 'y':
         elif response[0] == 'n':
             return False
         elif response == 'dc':
-            print '\n'.join(c_diff)
+            print('\n'.join(c_diff))
         elif response[0] == 'd':
-            print '\n'.join(u_diff)
+            print('\n'.join(u_diff))
         else:
-            print query_usage
+            print(query_usage)
 
 query_usage = """\
 Responses:
         return
     if os.system('svn info %r >/dev/null 2>&1' % parent) > 0:
         if verbosity > 1:
-            print '%sNot part of a svn working copy; cannot add directory' % pad
+            print('%sNot part of a svn working copy; cannot add directory' % pad)
         return
     cmd = ['svn', 'add', dir]
     if verbosity > 1:
-        print '%sRunning: %s' % (pad, ' '.join(cmd))
+        print('%sRunning: %s' % (pad, ' '.join(cmd)))
     proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
     stdout, stderr = proc.communicate()
     if verbosity > 1 and stdout:
-        print 'Script output:'
-        print stdout
+        print('Script output:')
+        print(stdout)
 
 def substitute_filename(fn, vars):
     for var, value in vars.items():
         tmpl = LaxTemplate(content)
         try:
             return tmpl.substitute(TypeMapper(v))
-        except Exception, e:
+        except Exception as e:
             _add_except(e, ' in file %s' % filename)
             raise
     if Cheetah is None:
     """
     try:
         return func(*args, **kw)
-    except SkipTemplate, e:
-        print 'Skipping file %s' % filename
+    except SkipTemplate as e:
+        print('Skipping file %s' % filename)
         if str(e):
-            print str(e)
+            print(str(e))
         raise
-    except Exception, e:
-        print 'Error in file %s:' % filename
+    except Exception as e:
+        print('Error in file %s:' % filename)
         if isinstance(e, NameError):
             items = vars.items()
             items.sort()
             for name, value in items:
-                print '%s = %r' % (name, value)
+                print('%s = %r' % (name, value))
         raise
 
 def html_quote(s):
 def url_quote(s):
     if s is None:
         return ''
-    return urllib.quote(str(s))
+    return quote(str(s))
 
 def test(conf, true_cond, false_cond=None):
     if conf:
 def eval_with_catch(expr, vars):
     try:
         return eval(expr, vars)
-    except Exception, e:
+    except Exception as e:
         _add_except(e, 'in expression %r' % expr)
         raise
 

File paste/script/create_distro.py

+from __future__ import print_function
 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 import re
 import sys
 import os
 import pkg_resources
-from command import Command, BadCommand
-import copydir
-import pluginlib
+from .command import Command, BadCommand
+from . import copydir
+from . import pluginlib
 import fnmatch
 try:
     set
         if self.options.list_variables:
             return self.list_variables(templates)
         if self.verbose:
-            print 'Selected and implied templates:'
+            print('Selected and implied templates:')
             max_tmpl_name = max([len(tmpl_name) for tmpl_name, tmpl in templates])
             for tmpl_name, tmpl in templates:
-                print '  %s%s  %s' % (
+                print('  %s%s  %s' % (
                     tmpl_name, ' '*(max_tmpl_name-len(tmpl_name)),
-                    tmpl.summary)
-            print
+                    tmpl.summary))
+            print()
         if not self.args:
             if self.interactive:
                 dist_name = self.challenge('Enter project name')
                              expect_returncode=True)
             found_setup_py = True
         elif self.verbose > 1:
-            print 'No setup.py (cannot run egg_info)'
+            print('No setup.py (cannot run egg_info)')
 
         package_dir = vars.get('package_dir', None)
         if package_dir:
             if len(egg_plugins) and (not os.path.exists(plugins_path) or \
                     os.path.getmtime(plugins_path) == paster_plugins_mtime):
                 if self.verbose:
-                    print >> sys.stderr, \
-                        ('Manually creating paster_plugins.txt (deprecated! '
-                         'pass a paster_plugins keyword to setup() instead)')
+                    print(('Manually creating paster_plugins.txt (deprecated! '
+                         'pass a paster_plugins keyword to setup() instead)'), file=sys.stderr)
                 for plugin in egg_plugins:
                     if self.verbose:
-                        print 'Adding %s to paster_plugins.txt' % plugin
+                        print('Adding %s to paster_plugins.txt' % plugin)
                     if not self.simulate:
                         pluginlib.add_plugin(egg_info_dir, plugin)
         
         
     def create_template(self, template, output_dir, vars):
         if self.verbose:
-            print 'Creating template %s' % template.name
+            print('Creating template %s' % template.name)
         template.run(self, output_dir, vars)
 
     def setup_svn_repository(self, output_dir, dist_name):
             'svn_command':svn_command,
         }
         if self.verbose:
-            print "Running:"
-            print cmd
+            print("Running:")
+            print(cmd)
         if not self.simulate:
             os.system(cmd)
         svn_repos_path_trunk = os.path.join(svn_repos_path,'trunk').replace('\\','/')
         cmd = svn_command+' co "%s" "%s"' % (svn_repos_path_trunk, output_dir)
         if self.verbose:
-            print "Running %s" % cmd
+            print("Running %s" % cmd)
         if not self.simulate:
             os.system(cmd)
 
     def display_vars(self, vars):
         vars = vars.items()
         vars.sort()
-        print 'Variables:'
+        print('Variables:')
         max_var = max([len(n) for n, v in vars])
         for name, value in vars:
-            print '  %s:%s  %s' % (
-                name, ' '*(max_var-len(name)), value)
+            print('  %s:%s  %s' % (
+                name, ' '*(max_var-len(name)), value))
         
     def list_templates(self):
         templates = []
         for entry in self.all_entry_points():
             try:
                 templates.append(entry.load()(entry.name))
-            except Exception, e:
+            except Exception as e:
                 # We will not be stopped!
-                print 'Warning: could not load entry point %s (%s: %s)' % (
-                    entry.name, e.__class__.__name__, e)
+                print('Warning: could not load entry point %s (%s: %s)' % (
+                    entry.name, e.__class__.__name__, e))
         max_name = max([len(t.name) for t in templates])
         templates.sort(lambda a, b: cmp(a.name, b.name))
-        print 'Available templates:'
+        print('Available templates:')
         for template in templates:
             # @@: Wrap description
-            print '  %s:%s  %s' % (
+            print('  %s:%s  %s' % (
                 template.name,
                 ' '*(max_name-len(template.name)),
-                template.summary)
+                template.summary))
         
     def inspect_files(self, output_dir, templates, vars):
         file_sources = {}
             for ext in self._ignore_filenames:
                 if fnmatch.fnmatch(name, ext):
                     if self.verbose > 1:
-                        print '%sIgnoring %s' % (pad, name)
+                        print('%sIgnoring %s' % (pad, name))
                     skip_this = True
                     break
             if skip_this:
             partial = os.path.join(join, name)
             if partial not in file_sources:
                 if self.verbose > 1:
-                    print '%s%s (not from template)' % (pad, name)
+                    print('%s%s (not from template)' % (pad, name))
                 continue
             templates = file_sources.pop(partial)
-            print '%s%s from:' % (pad, name)
+            print('%s%s from:' % (pad, name))
             for template in templates:
-                print '%s  %s' % (pad, template.name)
+                print('%s  %s' % (pad, template.name))
         for dir in dirs:
             if dir in self._ignore_dirs:
                 continue
-            print '%sRecursing into %s/' % (pad, dir)
+            print('%sRecursing into %s/' % (pad, dir))
             self._show_files(
                 output_dir, file_sources,
                 join=os.path.join(join, dir),
     def _show_leftovers(self, output_dir, file_sources):
         if not file_sources:
             return
-        print 
-        print 'These files were supposed to be generated by templates'
-        print 'but were not found:'
+        print() 
+        print('These files were supposed to be generated by templates')
+        print('but were not found:')
         file_sources = file_sources.items()
         file_sources.sort()
         for partial, templates in file_sources:
-            print '  %s from:' % partial
+            print('  %s from:' % partial)
             for template in templates:
-                print '    %s' % template.name
+                print('    %s' % template.name)
 
     def list_variables(self, templates):
         for tmpl_name, tmpl in templates:
 
     def _show_template_vars(self, tmpl_name, tmpl, message=None):
         title = '%s (from %s)' % (tmpl.name, tmpl_name)
-        print title
-        print '-'*len(title)
+        print(title)
+        print('-'*len(title))
         if message is not None:
-            print '  %s' % message
-            print
+            print('  %s' % message)
+            print()
             return
         tmpl.print_vars(indent=2)

File paste/script/entrypoints.py

+from __future__ import print_function
 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 import textwrap
 import os
 import pkg_resources
-from command import Command, BadCommand
+from .command import Command, BadCommand
 import fnmatch
 import re
 import traceback
-from cStringIO import StringIO
+from six.moves.cStringIO import StringIO
 import inspect
 import types
 
             ep_pat = self.get_pattern(self.args[1])
         for group in groups:
             desc = self.get_group_description(group)
-            print '[%s]' % group
+            print('[%s]' % group)
             if desc:
-                print self.wrap(desc)
-                print
+                print(self.wrap(desc))
+                print()
             by_dist = {}
             self.print_entry_points_by_group(group, ep_pat)
 
             if not entries:
                 continue
             if len(dists) > 1:
-                print '%s (+ %i older versions)' % (
-                    dist, len(dists)-1)
+                print('%s (+ %i older versions)' % (
+                    dist, len(dists)-1))
             else:
-                print '%s' % dist
+                print('%s' % dist)
             entries.sort(lambda a, b: cmp(a.name, b.name))
             for entry in entries:
-                print self._ep_description(entry)
+                print(self._ep_description(entry))
                 desc = self.get_entry_point_description(entry, group)
                 if desc and desc.description:
-                    print self.wrap(desc.description, indent=4)
+                    print(self.wrap(desc.description, indent=4))
 
     def show_egg(self, egg_name):
         group_pat = None
         for group, points in entry_groups:
             if group_pat and not group_pat.search(group):
                 continue
-            print '[%s]' % group
+            print('[%s]' % group)
             points = points.items()
             points.sort()
             for name, entry in points:
                 if ep_pat:
                     if not ep_pat.search(name):
                         continue
-                print self._ep_description(entry)
+                print(self._ep_description(entry))
                 desc = self.get_entry_point_description(entry, group)
                 if desc and desc.description:
-                    print self.wrap(desc.description, indent=2)
-                print
+                    print(self.wrap(desc.description, indent=2))
+                print()
 
     def wrap(self, text, indent=0):
         text = dedent(text)
     def list_entry_points(self):
         pattern = self.get_pattern(self.args and self.args[0])
         groups = self.get_groups_by_pattern(pattern)
-        print '%i entry point groups found:' % len(groups)
+        print('%i entry point groups found:' % len(groups))
         for group in groups:
             desc = self.get_group_description(group)
-            print '[%s]' % group
+            print('[%s]' % group)
             if desc:
                 if hasattr(desc, 'description'):
                     desc = desc.description
-                print self.wrap(desc, indent=2)
+                print(self.wrap(desc, indent=2))
 
     def get_groups_by_pattern(self, pattern):
         env = pkg_resources.Environment()
     def get_entry_point_description(self, ep, group):
         try:
             return self._safe_get_entry_point_description(ep, group)
-        except Exception, e:
+        except Exception as e:
             out = StringIO()
             traceback.print_exc(file=out)
             return ErrorDescription(e, out.getvalue())
         self.doc_object = doc_object
         self.description = dedent(self.doc_object.__doc__)
         try:
-            if isinstance(self.doc_object, (type, types.ClassType)):
-                func = self.doc_object.__init__.im_func
+            if isinstance(self.doc_object, type):
+                func = self.doc_object.__init__.__func__
             elif (hasattr(self.doc_object, '__call__')
                   and not isinstance(self.doc_object, types.FunctionType)):
                 func = self.doc_object.__call__

File paste/script/exe.py

 import sys
 import shlex
 import pkg_resources
-import command
+from . import command
 
 class ExeCommand(command.Command):
 
 
     def run(self, argv):
         if argv and argv[0] in ('-h', '--help'):
-            print self.description
+            print(self.description)
             return
         
         if os.environ.get('REQUEST_METHOD'):
             # Maybe import cgitb or something?
             
         if '_' not in os.environ:
-            print "Warning: this command is intended to be run with a #! like:"
-            print "  #!/usr/bin/env paster exe"
-            print "It only works with /usr/bin/env, and only as a #! line."
+            print("Warning: this command is intended to be run with a #! like:")
+            print("  #!/usr/bin/env paster exe")
+            print("It only works with /usr/bin/env, and only as a #! line.")
             # Should I actually shlex.split the args?
             filename = argv[-1]
             args = argv[:-1]

File paste/script/filemaker.py

 import pkg_resources
 from paste.script import pluginlib, copydir
 from paste.script.command import BadCommand
+from six.moves import input
 difflib = None
 try:
     import subprocess
         if not os.path.exists(dir):
             self.ensure_dir(os.path.dirname(dir), svn_add=svn_add, package=package)
             if self.verbose:
-                print 'Creating %s' % self.shorten(dir)
+                print('Creating %s' % self.shorten(dir))
             if not self.simulate:
                 os.mkdir(dir)
             if (svn_add and
                 f = open(initfile, 'wb')
                 f.write("#\n")
                 f.close()
-                print 'Creating %s' % self.shorten(initfile)
+                print('Creating %s' % self.shorten(initfile))
                 if (svn_add and
                     os.path.exists(os.path.join(os.path.dirname(dir), '.svn'))):
                     self.svn_command('add', initfile)
         else:
             if self.verbose > 1:
-                print "Directory already exists: %s" % self.shorten(dir)
+                print("Directory already exists: %s" % self.shorten(dir))
 
     def ensure_file(self, filename, content, svn_add=True, package=False):
         """
         self.ensure_dir(os.path.dirname(filename), svn_add=svn_add, package=package)
         if not os.path.exists(filename):
             if self.verbose:
-                print 'Creating %s' % filename
+                print('Creating %s' % filename)
             if not self.simulate:
                 f = open(filename, 'wb')
                 f.write(content)
         f.close()
         if content == old_content:
             if self.verbose > 1:
-                print 'File %s matches expected content' % filename
+                print('File %s matches expected content' % filename)
             return
         if self.interactive:
-            print 'Warning: file %s does not match expected content' % filename
+            print('Warning: file %s does not match expected content' % filename)
             if difflib is None:
                 import difflib
             diff = difflib.context_diff(
                 old_content.splitlines(),
                 'expected ' + filename,
                 filename)
-            print '\n'.join(diff)
+            print('\n'.join(diff))
             if self.interactive:
                 while 1:
-                    s = raw_input(
+                    s = input(
                         'Overwrite file with new content? [y/N] ').strip().lower()
                     if not s:
                         s = 'n'
                         break
                     if s.startswith('n'):
                         return
-                    print 'Unknown response; Y or N please'
+                    print('Unknown response; Y or N please')
             else:
                 return
                     
         if self.verbose:
-            print 'Overwriting %s with new content' % filename
+            print('Overwriting %s with new content' % filename)
         if not self.simulate:
             f = open(filename, 'wb')
             f.write(content)
         """
         try:
             return self.run_command('svn', *args, **kw)
-        except OSError, e:
+        except OSError as e:
             if not self._svn_failed:
-                print 'Unable to run svn command (%s); proceeding anyway' % e
+                print('Unable to run svn command (%s); proceeding anyway' % e)
                 self._svn_failed = True
 
     def run_command(self, cmd, *args, **kw):
                                     cwd=cwd,
                                     stderr=stderr_pipe,
                                     stdout=subprocess.PIPE)
-        except OSError, e:
+        except OSError as e:
             if e.errno != 2:
                 # File not found
                 raise
                 "The expected executable %s was not found (%s)"
                 % (cmd, e))
         if self.verbose:
-            print 'Running %s %s' % (cmd, ' '.join(args))
+            print('Running %s %s' % (cmd, ' '.join(args)))
         if self.simulate:
             return None
         stdout, stderr = proc.communicate()
         if proc.returncode and not expect_returncode:
             if not self.verbose:
-                print 'Running %s %s' % (cmd, ' '.join(args))
-            print 'Error (exit code: %s)' % proc.returncode
+                print('Running %s %s' % (cmd, ' '.join(args)))
+            print('Error (exit code: %s)' % proc.returncode)
             if stderr:
-                print stderr
+                print(stderr)
             raise OSError("Error executing command %s" % cmd)
         if self.verbose > 2:
             if stderr:
-                print 'Command error output:'
-                print stderr
+                print('Command error output:')
+                print(stderr)
             if stdout:
-                print 'Command output:'
-                print stdout
+                print('Command output:')
+                print(stdout)
         return stdout
 
 def popdefault(dict, name, default=None):

File paste/script/grep.py

 import marshal
 import inspect
 import re
-from command import Command
-import pluginlib
+from .command import Command
+from . import pluginlib
+from six.moves import range
 
 class GrepCommand(Command):
 
         self.basedir = os.path.dirname(
             pluginlib.find_egg_info_dir(os.getcwd()))
         if self.verbose:
-            print "Searching in %s" % self.basedir
+            print("Searching in %s" % self.basedir)
         self.total_files = 0
         self.search_dir(self.basedir)
         if self.verbose > 1:
-            print "Searched %i files" % self.total_files
+            print("Searched %i files" % self.total_files)
 
     def search_dir(self, dir):
         names = os.listdir(dir)
                 if not any:
                     any = True
                     if as_module:
-                        print '%s (unloadable)' % self.module_name(filename)
+                        print('%s (unloadable)' % self.module_name(filename))
                     else:
-                        print self.relative_name(filename)
-                print '  %3i  %s' % (lineno, line)
+                        print(self.relative_name(filename))
+                print('  %3i  %s' % (lineno, line))
                 if not self.verbose:
                     break
         f.close()
                 
     def found(self, code, filename, path):
-        print self.display(filename, path)
+        print(self.display(filename, path))
         self.find_occurance(code)
 
     def find_occurance(self, code):
         f = open(code.co_filename, 'rb')
         lineno = 0
-        for index, line in zip(xrange(code.co_firstlineno), f):
+        for index, line in zip(range(code.co_firstlineno), f):
             lineno += 1
             pass
         lines = []
                 else:
                     if this_indent < first_indent:
                         break
-                print '  %3i  %s' % (lineno, line[first_indent:].rstrip())
+                print('  %3i  %s' % (lineno, line[first_indent:].rstrip()))
                 if not self.verbose:
                     break
 

File paste/script/help.py

+from __future__ import print_function
 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
-from command import Command, get_commands
-from command import parser as base_parser
+from .command import Command, get_commands
+from .command import parser as base_parser
 
 class HelpCommand(Command):
 
         name = self.args[0]
         commands = get_commands()
         if name not in commands:
-            print 'No such command: %s' % name
+            print('No such command: %s' % name)
             self.generic_help()
             return
 
         
     def generic_help(self):
         base_parser.print_help()
-        print
+        print()
         commands_grouped = {}
         commands = get_commands()
         longest = max([len(n) for n in commands.keys()])
         for name, command in commands.items():
             try:
                 command = command.load()
-            except Exception, e:
-                print 'Cannot load command %s: %s' % (name, e)
+            except Exception as e:
+                print('Cannot load command %s: %s' % (name, e))
                 continue
             if getattr(command, 'hidden', False):
                 continue
                 command.group_name, []).append((name, command))
         commands_grouped = commands_grouped.items()
         commands_grouped.sort()
-        print 'Commands:'
+        print('Commands:')
         for group, commands in commands_grouped:
             if group:
-                print group + ':'
+                print(group + ':')
             commands.sort()
             for name, command in commands:
-                print '  %s  %s' % (self.pad(name, length=longest),
-                                    command.summary)
+                print('  %s  %s' % (self.pad(name, length=longest),
+                                    command.summary))
                 #if command.description:
                 #    print self.indent_block(command.description, 4)
-            print
+            print()
         

File paste/script/pluginlib.py

+from __future__ import print_function
 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 import os
             "Plugin %s not found in file %s (from: %s)"
             % (plugin_name, fn, lines))
     lines.remove(line)
-    print 'writing', lines
+    print('writing', lines)
     f = open(fn, 'w')
     for line in lines:
         f.write(line)
         plugin = plugin_list.pop()
         try:
             pkg_resources.require(plugin)
-        except pkg_resources.DistributionNotFound, e:
+        except pkg_resources.DistributionNotFound as e:
             msg = '%sNot Found%s: %s (did you run python setup.py develop?)'
             if str(e) != plugin:
                 e.args = (msg % (str(e) + ': ', ' for', plugin)),
             for add_plugin in parse_lines(data):
                 if add_plugin not in found:
                     plugin_list.append(add_plugin)
-    return map(get_distro, found)
+    return list(map(get_distro, found))
 
 def get_distro(spec):
     return pkg_resources.get_distribution(spec)

File paste/script/request.py

 import os
 import re
 import sys
-import urlparse
-import urllib
-from command import Command, BadCommand
+from six.moves.urllib.parse import quote
+from six.moves.urllib import parse
+
+from .command import Command, BadCommand
 from paste.deploy import loadapp, loadserver
 from paste.wsgilib import raw_interactive
 
         vars = {}
         app_spec = self.args[0]
         url = self.args[1]
-        url = urlparse.urljoin('/.command/', url)
+        url = urllib.parse.urljoin('/.command/', url)
         if self.options.config_vars:
             for item in self.option.config_vars:
                 if ':' not in item:
         qs = []
         for item in self.args[2:]:
             if '=' in item:
-                item = urllib.quote(item.split('=', 1)[0]) + '=' + urllib.quote(item.split('=', 1)[1])
+                item = quote(item.split('=', 1)[0]) + '=' + quote(item.split('=', 1)[1])
             else:
-                item = urllib.quote(item)
+                item = quote(item)
             qs.append(item)
         qs = '&'.join(qs)
         

File paste/script/serve.py

+from __future__ import print_function
 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 # @@: This should be moved to paste.deploy
     import subprocess
 except ImportError:
     from paste.util import subprocess24 as subprocess
-from command import Command, BadCommand
+from .command import Command, BadCommand
 from paste.deploy import loadapp, loadserver
 import threading
 import atexit
 import logging
-import ConfigParser
+from six.moves import configparser
 
 
 MAXFD = 1024
                 if os.environ.get(self._reloader_environ_key):
                     from paste import reloader
                     if self.verbose > 1:
-                        print 'Running reloading file monitor'
+                        print('Running reloading file monitor')
                     reloader.install(int(self.options.reload_interval))
                     if self.requires_config_file:
                         reloader.watch_file(self.args[0])
             result = self.stop_daemon()
             if result:
                 if cmd == 'restart':
-                    print "Could not stop daemon; aborting"
+                    print("Could not stop daemon; aborting")
                 else:
-                    print "Could not stop daemon"
+                    print("Could not stop daemon")
                 return result
             if cmd == 'stop':
                 return result
         if self.options.log_file:
             try:
                 writeable_log_file = open(self.options.log_file, 'a')
-            except IOError, ioe:
+            except IOError as ioe:
                 msg = 'Error: Unable to write to log file: %s' % ioe
                 raise BadCommand(msg)
             writeable_log_file.close()
         if self.options.pid_file:
             try:
                 writeable_pid_file = open(self.options.pid_file, 'a')
-            except IOError, ioe:
+            except IOError as ioe:
                 msg = 'Error: Unable to write to pid file: %s' % ioe
                 raise BadCommand(msg)
             writeable_pid_file.close()
         if getattr(self.options, 'daemon', False):
             try:
                 self.daemonize()
-            except DaemonizeException, ex:
+            except DaemonizeException as ex:
                 if self.verbose > 0:
-                    print str(ex)
+                    print(str(ex))
                 return
 
         if (self.options.monitor_restart
                                      relative_to=base, global_conf=vars)
             app = self.loadapp(app_spec, name=app_name,
                                relative_to=base, global_conf=vars)
-        except SyntaxError, e:
+        except SyntaxError as e:
             if self.options.reload and os.environ.get(self._reloader_environ_key):
                 traceback.print_exc()
                 reloader.watch_file(e.filename)
                 msg = 'Starting server in PID %i.' % os.getpid()
             else:
                 msg = 'Starting server.'
-            print msg
+            print(msg)
 
         def serve():
             try:
                 server(app)
-            except (SystemExit, KeyboardInterrupt), e:
+            except (SystemExit, KeyboardInterrupt) as e:
                 if self.verbose > 1:
                     raise
                 if str(e):
                     msg = ' '+str(e)
                 else:
                     msg = ''
-                print 'Exiting%s (-v to see traceback)' % msg
+                print('Exiting%s (-v to see traceback)' % msg)
 
         if jython_monitor:
             # JythonMonitor has to be ran from the main thread
             threading.Thread(target=serve).start()
-            print 'Starting Jython file monitor'
+            print('Starting Jython file monitor')
             jython_monitor.periodic_reload()
         else:
             serve()
                 % (pid, self.options.pid_file))
 
         if self.verbose > 0:
-            print 'Entering daemon mode'
+            print('Entering daemon mode')
         pid = os.fork()
         if pid:
             # The forked process also has a handle on resources, so we
     def record_pid(self, pid_file):
         pid = os.getpid()
         if self.verbose > 1:
-            print 'Writing PID %s to %s' % (pid, pid_file)
+            print('Writing PID %s to %s' % (pid, pid_file))
         f = open(pid_file, 'w')
         f.write(str(pid))
         f.close()
     def stop_daemon(self):
         pid_file = self.options.pid_file or 'paster.pid'
         if not os.path.exists(pid_file):
-            print 'No PID file exists in %s' % pid_file
+            print('No PID file exists in %s' % pid_file)
             return 1
         pid = read_pidfile(pid_file)
         if not pid:
-            print "Not a valid PID file in %s" % pid_file
+            print("Not a valid PID file in %s" % pid_file)
             return 1
         pid = live_pidfile(pid_file)
         if not pid:
-            print "PID in %s is not valid (deleting)" % pid_file
+            print("PID in %s is not valid (deleting)" % pid_file)
             try:
                 os.unlink(pid_file)
-            except (OSError, IOError), e:
-                print "Could not delete: %s" % e
+            except (OSError, IOError) as e:
+                print("Could not delete: %s" % e)
                 return 2
             return 1
         for j in range(10):
             os.kill(pid, signal.SIGTERM)
             time.sleep(1)
         else:
-            print "failed to kill web process %s" % pid
+            print("failed to kill web process %s" % pid)
             return 3
         if os.path.exists(pid_file):
             os.unlink(pid_file)
     def show_status(self):
         pid_file = self.options.pid_file or 'paster.pid'
         if not os.path.exists(pid_file):
-            print 'No PID file %s' % pid_file
+            print('No PID file %s' % pid_file)
             return 1
         pid = read_pidfile(pid_file)
         if not pid:
-            print 'No PID in file %s' % pid_file
+            print('No PID in file %s' % pid_file)
             return 1
         pid = live_pidfile(pid_file)
         if not pid:
-            print 'PID %s in %s is not running' % (pid, pid_file)
+            print('PID %s in %s is not running' % (pid, pid_file))
             return 1
-        print 'Server running in PID %s' % pid
+        print('Server running in PID %s' % pid)
         return 0
 
     def restart_with_reloader(self):
     def restart_with_monitor(self, reloader=False):
         if self.verbose > 0:
             if reloader:
-                print 'Starting subprocess with file monitor'
+                print('Starting subprocess with file monitor')
             else:
-                print 'Starting subprocess with monitor parent'
+                print('Starting subprocess with monitor parent')
         while 1:
             args = [self.quote_first_command_arg(sys.executable)] + sys.argv
             new_environ = os.environ.copy()
                     exit_code = proc.wait()
                     proc = None
                 except KeyboardInterrupt:
-                    print '^C caught in monitor process'
+                    print('^C caught in monitor process')
                     if self.verbose > 1:
                         raise
                     return 1
                 if exit_code != 3:
                     return exit_code
             if self.verbose > 0:
-                print '-'*20, 'Restarting', '-'*20
+                print('-'*20, 'Restarting', '-'*20)
 
     def change_user_group(self, user, group):
         if not user and not group:
                 gid = entry.pw_gid
             uid = entry.pw_uid
         if self.verbose > 0:
-            print 'Changing user to %s:%s (%s:%s)' % (
-                user, group or '(unknown)', uid, gid)
+            print('Changing user to %s:%s (%s:%s)' % (
+                user, group or '(unknown)', uid, gid))
         if hasattr(os, 'initgroups'):
             os.initgroups(user, gid)
         else:
         try:
             os.kill(int(pid), 0)
             return pid
-        except OSError, e:
+        except OSError as e:
             if e.errno == errno.EPERM:
                 return pid
     return None
         pass
     else:
         if pid_in_file != current_pid:
-            print "PID file %s contains %s, not expected PID %s" % (
-                filename, pid_in_file, current_pid)
+            print("PID file %s contains %s, not expected PID %s" % (
+                filename, pid_in_file, current_pid))
             return
     if verbosity > 0:
-        print "Removing PID file %s" % filename
+        print("Removing PID file %s" % filename)
     try:
         os.unlink(filename)
         return
-    except OSError, e:
+    except OSError as e:
         # Record, but don't give traceback
-        print "Cannot remove PID file: %s" % e
+        print("Cannot remove PID file: %s" % e)
     # well, at least lets not leave the invalid PID around...
     try:
         f = open(filename, 'w')
         f.write('')
         f.close()
-    except OSError, e:
-        print 'Stale PID left in file: %s (%e)' % (filename, e)
+    except OSError as e:
+        print('Stale PID left in file: %s (%e)' % (filename, e))
     else:
-        print 'Stale PID removed'
+        print('Stale PID removed')
 
 
 def ensure_port_cleanup(bound_addresses, maxtries=30, sleeptime=2):
             sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             try:
                 sock.connect(bound_address)
-            except socket.error, e:
+            except socket.error as e:
                 if e.args[0] != errno.ECONNREFUSED:
                     raise
                 break

File paste/script/templates.py

+from __future__ import print_function
 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 import sys
 import os
 import inspect
-import copydir
-import command
+from . import copydir
+from . import command
 
 from paste.util.template import paste_script_template_renderer
+import six
 
 class Template(object):
 
     def write_files(self, command, output_dir, vars):
         template_dir = self.template_dir()
         if not os.path.exists(output_dir):
-            print "Creating directory %s" % output_dir
+            print("Creating directory %s" % output_dir)
             if not command.simulate:
                 # Don't let copydir create this top-level directory,
                 # since copydir will svn add it sometimes:
         max_name = max([len(v.name) for v in vars])
         for var in vars:
             if var.description:
-                print '%s%s%s  %s' % (
+                print('%s%s%s  %s' % (
                     ' '*indent,
                     var.name,
                     ' '*(max_name-len(var.name)),
-                    var.description)
+                    var.description))
             else:
-                print '  %s' % var.name
+                print('  %s' % var.name)
             if var.default is not command.NoDefault:
-                print '      default: %r' % var.default
+                print('      default: %r' % var.default)
             if var.should_echo is True:
-                print '      should_echo: %s' % var.should_echo
-        print
+                print('      should_echo: %s' % var.should_echo)
+        print()
 
     print_vars = classmethod(print_vars)
 
                    'getmtime', 'trans']
 
 def find_args_in_template(template):
-    if isinstance(template, (str, unicode)):
+    if isinstance(template, six.string_types):
         # Treat as filename:
         import Cheetah.Template
         template = Cheetah.Template.Template(file=template)
             if found is None:
                 # Couldn't read variables
                 if verbose:
-                    print 'Template %s has no parseable variables' % full
+                    print('Template %s has no parseable variables' % full)
                 continue
             for var in found:
                 inner_vars[var.name] = var
             # Not a template, don't read it
             continue
         if verbose:
-            print 'Found variable(s) %s in Template %s' % (
-                ', '.join(inner_vars.keys()), full)
+            print('Found variable(s) %s in Template %s' % (
+                ', '.join(inner_vars.keys()), full))
         for var_name, var in inner_vars.items():
             # Easy case:
             if var_name not in all_vars:
                 cur_var.description = var.description
             elif (cur_var.description and var.description
                   and var.description != cur_var.description):
-                print >> sys.stderr, (
+                print((
                     "Variable descriptions do not match: %s: %s and %s"
-                    % (var_name, cur_var.description, var.description))
+                    % (var_name, cur_var.description, var.description)), file=sys.stderr)
             if (cur_var.default is not command.NoDefault
                 and var.default is not command.NoDefault
                 and cur_var.default != var.default):
-                print >> sys.stderr, (
+                print((
                     "Variable defaults do not match: %s: %r and %r"
-                    % (var_name, cur_var.default, var.default))
+                    % (var_name, cur_var.default, var.default)), file=sys.stderr)
     return all_vars
 

File paste/script/testapp.py

 # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 import cgi
 import os
+import six
 
 html_page_template = '''