5 Commits
288 changed files with 4029 additions and 1964 deletions
+9 -2
View File
@@ -15,10 +15,17 @@
/OBITools-1.2.8/
/OBITools-1.2.9/
/OBITools-1.2.10/
/.DS_Store
/OBITools-1.2.11/
/OBITools-1.2.12/
/OBITools-1.2.13/
/OBITools-py3/
/.DS_Store
/obitools.test.old/
/coucou
/toto.fasta
/OBITools-1.2.13/
convert_2to3.log
distutils_convert_2to3.log
setup.py.p2
requirements.txt.old
/distutils.ext3
/src3
@@ -3,5 +3,5 @@ def build_ext(*args,**kargs):
'''
Wrapper over the build_ext class to postpone the import of cython
'''
from build_ext import build_ext as _build_ext
from .build_ext import build_ext as _build_ext
return _build_ext(*args,**kargs)
+2 -2
View File
@@ -38,8 +38,8 @@ class build(ori_build):
('build_ctools', has_ctools),
('build_files', has_files),
('build_cexe', has_executables)] \
+ ori_build.sub_commands + \
[('build_sphinx',has_doc)]
+ ori_build.sub_commands # + \
# [('build_sphinx',has_doc)]
def run(self):
log.info('\n\nRunning obidistutils build process\n\n')
@@ -52,21 +52,20 @@ class build_cexe(build_ctools):
name of the built file (see --> build_files)
"""
sources = list(sources)
for i in xrange(len(sources)):
print exe_name,sources[i],
for i in range(len(sources)):
print(exe_name,sources[i], end=' ')
if sources[i][0]=='@':
try:
filename = self.built_files[sources[i][1:]]
except KeyError:
raise DistutilsSetupError, \
('The %s filename declared in the source '
raise DistutilsSetupError(('The %s filename declared in the source '
'files of the program %s have not been '
'built by the installation process') % (sources[i],
exe_name)
exe_name))
sources[i]=filename
print "changed to ",filename
print("changed to ",filename)
else:
print " ok"
print(" ok")
return sources
+12 -19
View File
@@ -124,30 +124,25 @@ class build_exe(Command):
just returns otherwise.
"""
if not isinstance(executables, list):
raise DistutilsSetupError, \
"'executables' option must be a list of tuples"
raise DistutilsSetupError("'executables' option must be a list of tuples")
for exe in executables:
if not isinstance(exe, tuple) and len(exe) != 2:
raise DistutilsSetupError, \
"each element of 'executables' must a 2-tuple"
raise DistutilsSetupError("each element of 'executables' must a 2-tuple")
name, build_info = exe
if not isinstance(name, str):
raise DistutilsSetupError, \
"first element of each tuple in 'executables' " + \
"must be a string (the executables name)"
raise DistutilsSetupError("first element of each tuple in 'executables' " + \
"must be a string (the executables name)")
if '/' in name or (os.sep != '/' and os.sep in name):
raise DistutilsSetupError, \
("bad executable name '%s': " +
raise DistutilsSetupError(("bad executable name '%s': " +
"may not contain directory separators") % \
exe[0]
exe[0])
if not isinstance(build_info, dict):
raise DistutilsSetupError, \
"second element of each tuple in 'executables' " + \
"must be a dictionary (build info)"
raise DistutilsSetupError("second element of each tuple in 'executables' " + \
"must be a dictionary (build info)")
def get_executable_names(self):
# Assume the executables list is valid -- 'check_executable_list()' is
@@ -167,10 +162,9 @@ class build_exe(Command):
for (exe_name, build_info) in self.executables:
sources = build_info.get('sources')
if sources is None or not isinstance(sources, (list, tuple)):
raise DistutilsSetupError, \
("in 'executables' option (library '%s'), "
raise DistutilsSetupError(("in 'executables' option (library '%s'), "
"'sources' must be present and must be "
"a list of source filenames") % exe_name
"a list of source filenames") % exe_name)
filenames.extend(sources)
return filenames
@@ -182,10 +176,9 @@ class build_exe(Command):
for (exe_name, build_info) in executables:
sources = build_info.get('sources')
if sources is None or not isinstance(sources, (list, tuple)):
raise DistutilsSetupError, \
("in 'executables' option (library '%s'), " +
raise DistutilsSetupError(("in 'executables' option (library '%s'), " +
"'sources' must be present and must be " +
"a list of source filenames") % exe_name
"a list of source filenames") % exe_name)
sources = self.substitute_sources(exe_name,sources)
log.info("building '%s' program", exe_name)
@@ -23,7 +23,7 @@ from distutils.errors import DistutilsSetupError
class build_ext(ori_build_ext):
def modifyDocScripts(self):
print >>open("doc/sphinx/build_dir.txt","w"),self.build_lib
print(self.build_lib, file=open("doc/sphinx/build_dir.txt","w"))
def initialize_options(self):
ori_build_ext.initialize_options(self) # @UndefinedVariable
@@ -54,8 +54,8 @@ class build_ext(ori_build_ext):
name of the built file (see --> build_files)
"""
sources = list(sources)
for i in xrange(len(sources)):
print exe_name,sources[i],
for i in range(len(sources)):
print(exe_name,sources[i], end=' ')
if sources[i][0]=='@':
try:
filename = self.built_files[sources[i][1:]]
@@ -64,15 +64,14 @@ class build_ext(ori_build_ext):
if os.path.isfile (tmpfilename):
filename = tmpfilename
else:
raise DistutilsSetupError, \
('The %s filename declared in the source '
raise DistutilsSetupError(('The %s filename declared in the source '
'files of the program %s have not been '
'built by the installation process') % (sources[i],
exe_name)
exe_name))
sources[i]=filename
print "changed to ",filename
print("changed to ",filename)
else:
print " ok"
print(" ok")
return sources
@@ -85,7 +84,7 @@ class build_ext(ori_build_ext):
self.check_extensions_list(self.extensions)
for ext in self.extensions:
print "#####>",ext.sources
print("#####>",ext.sources)
ext.sources = self.cython_sources(ext.sources, ext)
self.build_extension(ext)
@@ -7,29 +7,31 @@ Created on 20 oct. 2012
import os.path
from distutils.command.build_scripts import build_scripts as ori_build_scripts,\
first_line_re
first_line_re
from distutils.util import convert_path
from distutils import log, sysconfig
from distutils.dep_util import newer
from stat import ST_MODE
import tokenize
class build_scripts(ori_build_scripts):
def copy_scripts (self):
"""Copy each script listed in 'self.scripts'; if it's marked as a
def copy_scripts(self):
r"""Copy each script listed in 'self.scripts'; if it's marked as a
Python script in the Unix way (first line matches 'first_line_re',
ie. starts with "\#!" and contains "python"), then adjust the first
line to refer to the current Python interpreter as we copy.
"""
"""
self.mkpath(self.build_dir)
rawbuild_dir = os.path.join(os.path.dirname(self.build_dir),'raw_scripts')
self.mkpath(rawbuild_dir)
updated_files = []
outfiles = []
for script in self.scripts:
adjust = 0
adjust = False
script = convert_path(script)
outfile = os.path.join(self.build_dir, os.path.splitext(os.path.basename(script))[0])
rawoutfile = os.path.join(rawbuild_dir, os.path.basename(script))
@@ -39,16 +41,18 @@ class build_scripts(ori_build_scripts):
log.debug("not copying %s (up-to-date)", script)
continue
# Always open the file but ignore failures in dry-run mode --
# Always open the file, but ignore failures in dry-run mode --
# that way, we'll get accurate feedback if we can read the
# script.
try:
f = open(script, "r")
except IOError:
f = open(script, "rb")
except OSError:
if not self.dry_run:
raise
f = None
else:
encoding, lines = tokenize.detect_encoding(f.readline)
f.seek(0)
first_line = f.readline()
if not first_line:
self.warn("%s is an empty file (skipping)" % script)
@@ -56,8 +60,8 @@ class build_scripts(ori_build_scripts):
match = first_line_re.match(first_line)
if match:
adjust = 1
post_interp = match.group(1) or ''
adjust = True
post_interp = match.group(1) or b''
log.info("Store the raw script %s -> %s", script,rawoutfile)
self.copy_file(script, rawoutfile)
@@ -66,26 +70,47 @@ class build_scripts(ori_build_scripts):
if adjust:
log.info("copying and adjusting %s -> %s", script,
self.build_dir)
updated_files.append(outfile)
if not self.dry_run:
outf = open(outfile, "w")
if not sysconfig.python_build:
outf.write("#!%s%s\n" %
(self.executable,
post_interp))
executable = self.executable
else:
outf.write("#!%s%s\n" %
(os.path.join(
executable = os.path.join(
sysconfig.get_config_var("BINDIR"),
"python%s%s" % (sysconfig.get_config_var("VERSION"),
sysconfig.get_config_var("EXE"))),
post_interp))
outf.writelines(f.readlines())
outf.close()
sysconfig.get_config_var("EXE")))
executable = os.fsencode(executable)
shebang = b"#!" + executable + post_interp + b"\n"
# Python parser starts to read a script using UTF-8 until
# it gets a #coding:xxx cookie. The shebang has to be the
# first line of a file, the #coding:xxx cookie cannot be
# written before. So the shebang has to be decodable from
# UTF-8.
try:
shebang.decode('utf-8')
except UnicodeDecodeError:
raise ValueError(
"The shebang ({!r}) is not decodable "
"from utf-8".format(shebang))
# If the script is encoded to a custom encoding (use a
# #coding:xxx cookie), the shebang has to be decodable from
# the script encoding too.
try:
shebang.decode(encoding)
except UnicodeDecodeError:
raise ValueError(
"The shebang ({!r}) is not decodable "
"from the script encoding ({})"
.format(shebang, encoding))
with open(outfile, "wb") as outf:
outf.write(shebang)
outf.writelines(f.readlines())
if f:
f.close()
else:
if f:
f.close()
updated_files.append(outfile)
self.copy_file(script, outfile)
if os.name == 'posix':
@@ -93,10 +118,11 @@ class build_scripts(ori_build_scripts):
if self.dry_run:
log.info("changing mode of %s", F)
else:
oldmode = os.stat(F)[ST_MODE] & 07777
newmode = (oldmode | 0555) & 07777
oldmode = os.stat(F)[ST_MODE] & 0o7777
newmode = (oldmode | 0o555) & 0o7777
if newmode != oldmode:
log.info("changing mode of %s from %o to %o",
F, oldmode, newmode)
os.chmod(F, newmode)
# XXX should we modify self.outfiles?
return outfiles, updated_files
@@ -18,7 +18,7 @@ class install(install_ori):
def __init__(self,dist):
install_ori.__init__(self, dist)
self.sub_commands.insert(0, ('build',lambda self: True))
self.sub_commands.append(('install_sphinx',lambda self: self.distribution.serenity))
# self.sub_commands.append(('install_sphinx',lambda self: self.distribution.serenity))
def run(self):
log.info('\n\nRunning obidistutils install process\n\n')
+14 -10
View File
@@ -4,13 +4,6 @@ Created on 20 oct. 2012
@author: coissac
'''
from os import path
import os.path
import glob
import sys
from obidistutils.command.sdist import sdist
try:
from setuptools import setup as ori_setup
from setuptools.command.egg_info import egg_info
@@ -19,6 +12,14 @@ except ImportError:
from distutils.core import setup as ori_setup
has_setuptools = False
from os import path
import os.path
import glob
import sys
from obidistutils.command.sdist import sdist
from distutils import log
from distutils.extension import Extension
from obidistutils.command.build import build
@@ -67,7 +68,7 @@ def findCython(root,base=None,pyrexs=None):
if y[0] !='@' else y.strip()
for y in cfiles]
print "@@@@>",cfiles
print("@@@@>",cfiles)
incdir = set(os.path.dirname(x) for x in cfiles if x[-2:]==".h")
cfiles = [x for x in cfiles if x[-2:]==".c"]
pyrexs[-1].sources.extend(cfiles)
@@ -77,10 +78,11 @@ def findCython(root,base=None,pyrexs=None):
except IOError:
pass
pyrexs[-1].sources.extend(glob.glob(os.path.splitext(pyrex)[0]+'.ext.*.c'))
print pyrexs[-1].sources
print(pyrexs[-1].sources)
# Main.compile([pyrex],timestamps=True)
pyrexs.extend(findCython(path.join(root,module),base+[module]))
print(pyrexs)
return pyrexs
def findC(root,base=None,pyrexs=None):
@@ -109,7 +111,7 @@ def findC(root,base=None,pyrexs=None):
except IOError:
pass
pyrexs[-1].sources.extend(glob.glob(os.path.splitext(pyrex)[0]+'.ext.*.c'))
print pyrexs[-1].sources
print(pyrexs[-1].sources)
pyrexs.extend(findC(path.join(root,module),base+[module]))
return pyrexs
@@ -173,6 +175,8 @@ def setup(**attrs):
if 'packages' not in attrs:
attrs['packages'] = findPackage(SRC)
log.debug(attrs['packages'])
if 'cmdclass' not in attrs:
attrs['cmdclass'] = COMMANDS
@@ -9,7 +9,7 @@ import os
import subprocess
import re
from distutils.errors import DistutilsError
import urllib2
import urllib.request, urllib.error, urllib.parse
import tempfile
import importlib
@@ -20,7 +20,7 @@ import argparse
import base64
from checkpython import is_mac_system_python, \
from .checkpython import is_mac_system_python, \
is_python27, \
is_a_virtualenv_python, \
which_virtualenv, \
@@ -50,7 +50,7 @@ def serenity_snake(envname,package,version,minversion=PIP_MINVERSION):
log.info("Installing %s (%s) in serenity mode" % (package,version))
print >>sys.stderr,snake
print(snake, file=sys.stderr)
sys.stderr.flush()
enforce_good_python()
@@ -140,7 +140,7 @@ def parse_package_requirement(requirement):
if requirement_relation is not None:
requirement_relation=requirement_relation.group(0)
except:
raise DistutilsError,"Requirement : %s not correctly formated" % requirement
raise DistutilsError("Requirement : %s not correctly formated" % requirement)
return requirement_project,requirement_relation,requirement_version
@@ -48,7 +48,7 @@ def get_a_cython_module(pip=None):
log.debug('temp install dir : %s' % tmpdir)
if ok!=0:
raise DistutilsError, "I cannot install a cython package"
raise DistutilsError("I cannot install a cython package")
f, filename, description = imp.find_module('Cython', [tmpdir])
@@ -91,7 +91,7 @@ def autocomplete():
subcommands += [i.get_opt_string() for i in opts
if i.help != optparse.SUPPRESS_HELP]
print(' '.join([x for x in subcommands if x.startswith(current)]))
print((' '.join([x for x in subcommands if x.startswith(current)])))
sys.exit(1)
@@ -5,4 +5,4 @@ depend on something external.
Files inside of pip._vendor should be considered immutable and should only be
updated to versions from upstream.
"""
from __future__ import absolute_import
@@ -513,7 +513,7 @@ def get_archive_formats():
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
list(_ARCHIVE_FORMATS.items())]
formats.sort()
return formats
@@ -603,7 +603,7 @@ def get_unpack_formats():
(name, extensions, description)
"""
formats = [(name, info[0], info[3]) for name, info in
_UNPACK_FORMATS.items()]
list(_UNPACK_FORMATS.items())]
formats.sort()
return formats
@@ -611,7 +611,7 @@ def _check_unpack_options(extensions, function, extra_args):
"""Checks what gets registered as an unpacker."""
# first make sure no other unpacker is registered for this extension
existing_extensions = {}
for name, info in _UNPACK_FORMATS.items():
for name, info in list(_UNPACK_FORMATS.items()):
for ext in info[0]:
existing_extensions[ext] = name
@@ -718,7 +718,7 @@ if _BZ2_SUPPORTED:
"bzip2'ed tar-file")
def _find_unpack_format(filename):
for name, info in _UNPACK_FORMATS.items():
for name, info in list(_UNPACK_FORMATS.items()):
for extension in info[0]:
if filename.endswith(extension):
return name
@@ -13,7 +13,7 @@ from os.path import pardir, realpath
try:
import configparser
except ImportError:
import ConfigParser as configparser
import configparser as configparser
__all__ = [
@@ -147,8 +147,8 @@ def _subst_vars(path, local_vars):
def _extend_dict(target_dict, other_dict):
target_keys = target_dict.keys()
for key, value in other_dict.items():
target_keys = list(target_dict.keys())
for key, value in list(other_dict.items()):
if key in target_keys:
continue
target_dict[key] = value
@@ -321,7 +321,7 @@ def _parse_makefile(filename, vars=None):
variables.remove(name)
# strip spurious spaces
for k, v in done.items():
for k, v in list(done.items()):
if isinstance(v, str):
done[k] = v.strip()
@@ -769,15 +769,15 @@ def get_python_version():
def _print_dict(title, data):
for index, (key, value) in enumerate(sorted(data.items())):
if index == 0:
print('%s: ' % (title))
print('\t%s = "%s"' % (key, value))
print(('%s: ' % (title)))
print(('\t%s = "%s"' % (key, value)))
def _main():
"""Display all information sysconfig detains."""
print('Platform: "%s"' % get_platform())
print('Python version: "%s"' % get_python_version())
print('Current installation scheme: "%s"' % _get_default_scheme())
print(('Platform: "%s"' % get_platform()))
print(('Python version: "%s"' % get_python_version()))
print(('Current installation scheme: "%s"' % _get_default_scheme()))
print()
_print_dict('Paths', get_paths())
print()
@@ -25,7 +25,7 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
from __future__ import print_function
"""Read from and write to tar format archives.
"""
@@ -33,10 +33,10 @@ from __future__ import print_function
__version__ = "$Revision$"
version = "0.9.0"
__author__ = "Lars Gust\u00e4bel (lars@gustaebel.de)"
__author__ = "Lars Gust\\u00e4bel (lars@gustaebel.de)"
__date__ = "$Date: 2011-02-25 17:42:01 +0200 (Fri, 25 Feb 2011) $"
__cvsid__ = "$Id: tarfile.py 88586 2011-02-25 15:42:01Z marc-andre.lemburg $"
__credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend."
__credits__ = "Gustavo Niemeyer, Niels Gust\\u00e4bel, Richard Townsend."
#---------
# Imports
@@ -68,7 +68,7 @@ except NameError:
__all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"]
if sys.version_info[0] < 3:
import __builtin__ as builtins
import builtins as builtins
else:
import builtins
@@ -1174,7 +1174,7 @@ class TarInfo(object):
# Check if one of the fields contains surrogate characters and thereby
# forces hdrcharset=BINARY, see _proc_pax() for more information.
binary = False
for keyword, value in pax_headers.items():
for keyword, value in list(pax_headers.items()):
try:
value.encode("utf8", "strict")
except UnicodeEncodeError:
@@ -1186,7 +1186,7 @@ class TarInfo(object):
# Put the hdrcharset field at the beginning of the header.
records += b"21 hdrcharset=BINARY\n"
for keyword, value in pax_headers.items():
for keyword, value in list(pax_headers.items()):
keyword = keyword.encode("utf8")
if binary:
# Try to restore the original byte representation of `value'.
@@ -1519,7 +1519,7 @@ class TarInfo(object):
"""Replace fields with supplemental information from a previous
pax extended or global header.
"""
for keyword, value in pax_headers.items():
for keyword, value in list(pax_headers.items()):
if keyword == "GNU.sparse.name":
setattr(self, "path", value)
elif keyword == "GNU.sparse.size":
@@ -1670,7 +1670,7 @@ class TarFile(object):
try:
if self.mode == "r":
self.firstmember = None
self.firstmember = self.next()
self.firstmember = next(self)
if self.mode == "a":
# Move to the end of the archive,
@@ -2076,7 +2076,7 @@ class TarFile(object):
# Change or exclude the TarInfo object.
if filter is not None:
tarinfo = filter(tarinfo)
tarinfo = list(filter(tarinfo))
if tarinfo is None:
self._dbg(2, "tarfile: Excluded %r" % name)
return
@@ -2411,7 +2411,7 @@ class TarFile(object):
raise ExtractError("could not change modification time")
#--------------------------------------------------------------------------
def next(self):
def __next__(self):
"""Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.
@@ -2488,7 +2488,7 @@ class TarFile(object):
members.
"""
while True:
tarinfo = self.next()
tarinfo = next(self)
if tarinfo is None:
break
self._loaded = True
@@ -2575,7 +2575,7 @@ class TarIter(object):
# happen that getmembers() is called during iteration,
# which will cause TarIter to stop prematurely.
if not self.tarfile._loaded:
tarinfo = self.tarfile.next()
tarinfo = next(self.tarfile)
if not tarinfo:
self.tarfile._loaded = True
raise StopIteration
@@ -4,42 +4,42 @@
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import absolute_import
import os
import re
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
string_types = basestring,
text_type = unicode
from io import StringIO
string_types = str,
text_type = str
from types import FileType as file_type
import __builtin__ as builtins
import ConfigParser as configparser
import builtins as builtins
import configparser as configparser
from ._backport import shutil
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit
from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit
from urllib import (urlretrieve, quote as _quote, unquote, url2pathname,
pathname2url, ContentTooShortError, splittype)
def quote(s):
if isinstance(s, unicode):
if isinstance(s, str):
s = s.encode('utf-8')
return _quote(s)
import urllib2
import urllib.request, urllib.error, urllib.parse
from urllib2 import (Request, urlopen, URLError, HTTPError,
HTTPBasicAuthHandler, HTTPPasswordMgr,
HTTPSHandler, HTTPHandler, HTTPRedirectHandler,
build_opener)
import httplib
import xmlrpclib
import Queue as queue
from HTMLParser import HTMLParser
import htmlentitydefs
import http.client
import xmlrpc.client
import queue as queue
from html.parser import HTMLParser
import html.entities
raw_input = raw_input
from itertools import ifilter as filter
from itertools import ifilterfalse as filterfalse
from itertools import filterfalse as filterfalse
_userprog = None
def splituser(host):
@@ -580,9 +580,9 @@ except ImportError: # pragma: no cover
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.
# Passes Python2.7's test suite and incorporates all the latest updates.
try:
from thread import get_ident as _get_ident
from _thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
from _dummy_thread import get_ident as _get_ident
try:
from _abcoll import KeysView, ValuesView, ItemsView
@@ -656,7 +656,7 @@ except ImportError: # pragma: no cover
def clear(self):
'od.clear() -> None. Remove all items from od.'
try:
for node in self.__map.itervalues():
for node in self.__map.values():
del node[:]
root = self.__root
root[:] = [root, root, None]
@@ -739,12 +739,12 @@ except ImportError: # pragma: no cover
for key in other:
self[key] = other[key]
elif hasattr(other, 'keys'):
for key in other.keys():
for key in list(other.keys()):
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
for key, value in list(kwds.items()):
self[key] = value
__update = update # let subclasses override update without breaking __init__
@@ -781,7 +781,7 @@ except ImportError: # pragma: no cover
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
finally:
del _repr_running[call_key]
@@ -816,7 +816,7 @@ except ImportError: # pragma: no cover
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return len(self)==len(other) and list(self.items()) == list(other.items())
return dict.__eq__(self, other)
def __ne__(self, other):
@@ -1053,7 +1053,7 @@ except ImportError: # pragma: no cover
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
result = c(**kwargs)
if props:
for name, value in props.items():
for name, value in list(props.items()):
setattr(result, name, value)
return result
@@ -5,7 +5,7 @@
#
"""PEP 376 implementation."""
from __future__ import unicode_literals
import base64
import codecs
@@ -205,11 +205,11 @@ class DistributionPath(object):
else:
self._generate_cache()
for dist in self._cache.path.values():
for dist in list(self._cache.path.values()):
yield dist
if self._include_egg:
for dist in self._cache_egg.path.values():
for dist in list(self._cache_egg.path.values()):
yield dist
def get_distribution(self, name):
@@ -298,7 +298,7 @@ class DistributionPath(object):
if name in d:
yield d[name]
else:
for v in d.values():
for v in list(d.values()):
yield v
@@ -1125,7 +1125,7 @@ class DependencyGraph(object):
disconnected = []
f.write("digraph dependencies {\n")
for dist, adjs in self.adjacency_list.items():
for dist, adjs in list(self.adjacency_list.items()):
if len(adjs) == 0 and not skip_disconnected:
disconnected.append(dist)
for other, label in adjs:
@@ -1156,7 +1156,7 @@ class DependencyGraph(object):
result = []
# Make a shallow copy of the adjacency list
alist = {}
for k, v in self.adjacency_list.items():
for k, v in list(self.adjacency_list.items()):
alist[k] = v[:]
while True:
# See what we can remove in this run
@@ -1169,7 +1169,7 @@ class DependencyGraph(object):
# What's left in alist (if anything) is a cycle.
break
# Remove from the adjacency list of others
for k, v in alist.items():
for k, v in list(alist.items()):
alist[k] = [(d, r) for d, r in v if d not in to_remove]
logger.debug('Moving to result: %s',
['%s (%s)' % (d.name, d.version) for d in to_remove])
@@ -1179,7 +1179,7 @@ class DependencyGraph(object):
def __repr__(self):
"""Representation of the graph"""
output = []
for dist, adjs in self.adjacency_list.items():
for dist, adjs in list(self.adjacency_list.items()):
output.append(self.repr_node(dist))
return '\n'.join(output)
@@ -124,10 +124,10 @@ class PackageIndex(object):
metadata.validate()
d = metadata.todict()
d[':action'] = 'verify'
request = self.encode_request(d.items(), [])
request = self.encode_request(list(d.items()), [])
response = self.send_request(request)
d[':action'] = 'submit'
request = self.encode_request(d.items(), [])
request = self.encode_request(list(d.items()), [])
return self.send_request(request)
def _reader(self, name, stream, outbuf):
@@ -275,7 +275,7 @@ class PackageIndex(object):
files.append(('gpg_signature', os.path.basename(sig_file),
sig_data))
shutil.rmtree(os.path.dirname(sig_file))
request = self.encode_request(d.items(), files)
request = self.encode_request(list(d.items()), files)
return self.send_request(request)
def upload_documentation(self, metadata, doc_dir):
@@ -7,7 +7,7 @@
Supports all metadata formats (1.0, 1.1, 1.2, and 2.0 experimental).
"""
from __future__ import unicode_literals
import codecs
from email import message_from_file
@@ -120,7 +120,7 @@ def _best_version(fields):
return False
keys = []
for key, value in fields.items():
for key, value in list(fields.items()):
if value in ([], 'UNKNOWN', None):
continue
keys.append(key)
@@ -401,14 +401,14 @@ class LegacyMetadata(object):
# other is None or empty container
pass
elif hasattr(other, 'keys'):
for k in other.keys():
for k in list(other.keys()):
_set(k, other[k])
else:
for k, v in other:
_set(k, v)
if kwargs:
for k, v in kwargs.items():
for k, v in list(kwargs.items()):
_set(k, v)
def set(self, name, value):
@@ -602,14 +602,14 @@ class LegacyMetadata(object):
return list(_version2fieldlist(self['Metadata-Version']))
def __iter__(self):
for key in self.keys():
for key in list(self.keys()):
yield key
def values(self):
return [self[key] for key in self.keys()]
return [self[key] for key in list(self.keys())]
def items(self):
return [(key, self[key]) for key in self.keys()]
return [(key, self[key]) for key in list(self.keys())]
def __repr__(self):
return '<%s %s %s>' % (self.__class__.__name__, self.name,
@@ -875,14 +875,14 @@ class Metadata(object):
if mapping.get('metadata_version') != self.METADATA_VERSION:
raise MetadataUnrecognizedVersionError()
missing = []
for key, exclusions in self.MANDATORY_KEYS.items():
for key, exclusions in list(self.MANDATORY_KEYS.items()):
if key not in mapping:
if scheme not in exclusions:
missing.append(key)
if missing:
msg = 'Missing metadata items: %s' % ', '.join(missing)
raise MetadataMissingError(msg)
for k, v in mapping.items():
for k, v in list(mapping.items()):
self._validate_value(k, v, scheme)
def validate(self):
@@ -964,7 +964,7 @@ class Metadata(object):
assert self._data and not self._legacy
result = LegacyMetadata()
nmd = self._data
for nk, ok in self.LEGACY_MAPPING.items():
for nk, ok in list(self.LEGACY_MAPPING.items()):
if nk in nmd:
result[ok] = nmd[nk]
r1 = process_entries(self.run_requires + self.meta_requires)
@@ -4,7 +4,7 @@
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import bisect
import io
@@ -165,7 +165,7 @@ def get_executable():
def proceed(prompt, allowed_chars, error_prompt=None, default=None):
p = prompt
while True:
s = raw_input(p)
s = input(p)
p = prompt
if not s and default:
s = default
@@ -197,8 +197,8 @@ def read_exports(stream):
try:
data = json.load(stream)
result = data['exports']
for group, entries in result.items():
for k, v in entries.items():
for group, entries in list(result.items()):
for k, v in list(entries.items()):
s = '%s = %s' % (k, v)
entry = get_export_entry(s)
assert entry is not None
@@ -228,10 +228,10 @@ def write_exports(exports, stream):
# needs to be a text stream
stream = codecs.getwriter('utf-8')(stream)
cp = configparser.ConfigParser()
for k, v in exports.items():
for k, v in list(exports.items()):
# TODO check k, v for valid values
cp.add_section(k)
for entry in v.values():
for entry in list(v.values()):
if entry.suffix is None:
s = entry.prefix
else:
@@ -1445,7 +1445,7 @@ class CSVReader(CSVBase):
def __iter__(self):
return self
def next(self):
def __next__(self):
result = next(self.reader)
if sys.version_info[0] < 3:
for i, item in enumerate(result):
@@ -1510,7 +1510,7 @@ class Configurator(BaseConfigurator):
kwargs = dict(items)
result = c(*args, **kwargs)
if props:
for n, v in props.items():
for n, v in list(props.items()):
setattr(result, n, convert(v))
return result
@@ -4,7 +4,7 @@
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import base64
import codecs
@@ -313,7 +313,7 @@ class Wheel(object):
if tags is None:
tags = {}
libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0]
libkey = list([o for o in ('purelib', 'platlib') if o in paths])[0]
if libkey == 'platlib':
is_pure = 'false'
default_pyver = [IMPVER]
@@ -574,7 +574,7 @@ class Wheel(object):
k = '%s_scripts' % key
if k in epdata:
commands['wrap_%s' % key] = d = {}
for v in epdata[k].values():
for v in list(epdata[k].values()):
s = '%s:%s' % (v.prefix, v.suffix)
if v.flags:
s += ' %s' % v.flags
@@ -600,14 +600,14 @@ class Wheel(object):
raise ValueError('Valid script path not '
'specified')
maker.target_dir = script_dir
for k, v in console_scripts.items():
for k, v in list(console_scripts.items()):
script = '%s = %s' % (k, v)
filenames = maker.make(script)
fileop.set_executable_mode(filenames)
if gui_scripts:
options = {'gui': True }
for k, v in gui_scripts.items():
for k, v in list(gui_scripts.items()):
script = '%s = %s' % (k, v)
filenames = maker.make(script, options)
fileop.set_executable_mode(filenames)
@@ -661,7 +661,7 @@ class Wheel(object):
cache_base = os.path.join(cache.base, prefix)
if not os.path.isdir(cache_base):
os.makedirs(cache_base)
for name, relpath in extensions.items():
for name, relpath in list(extensions.items()):
dest = os.path.join(cache_base, convert_path(relpath))
if not os.path.exists(dest):
extract = True
@@ -11,7 +11,7 @@ f = open("my_document.html")
tree = html5lib.parse(f)
"""
from __future__ import absolute_import, division, unicode_literals
from .html5parser import HTMLParser, parse, parseFragment
from .treebuilders import getTreeBuilder
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
import string
import gettext
@@ -449,7 +449,7 @@ adjustForeignAttributes = {
}
unadjustForeignAttributes = dict([((ns, local), qname) for qname, (prefix, local, ns) in
adjustForeignAttributes.items()])
list(adjustForeignAttributes.items())])
spaceCharacters = frozenset((
"\t",
@@ -3092,7 +3092,7 @@ tagTokenTypes = frozenset((tokenTypes["StartTag"], tokenTypes["EndTag"],
tokenTypes["EmptyTag"]))
prefixes = dict([(v, k) for k, v in namespaces.items()])
prefixes = dict([(v, k) for k, v in list(namespaces.items())])
prefixes["http://www.w3.org/1998/Math/MathML"] = "math"
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
class Filter(object):
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from . import _base
@@ -13,7 +13,7 @@ class Filter(_base.Filter):
for token in _base.Filter.__iter__(self):
if token["type"] in ("StartTag", "EmptyTag"):
attrs = OrderedDict()
for name, value in sorted(token["data"].items(),
for name, value in sorted(list(token["data"].items()),
key=lambda x: x[0]):
attrs[name] = value
token["data"] = attrs
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from . import _base
@@ -23,7 +23,7 @@ class Filter(_base.Filter):
if token["name"].lower() == "meta":
# replace charset with actual encoding
has_http_equiv_content_type = False
for (namespace, name), value in token["data"].items():
for (namespace, name), value in list(token["data"].items()):
if namespace is not None:
continue
elif name.lower() == 'charset':
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from gettext import gettext
_ = gettext
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from . import _base
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from . import _base
from ..sanitizer import HTMLSanitizerMixin
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
import re
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import with_metaclass
import types
@@ -38,7 +38,7 @@ def parseFragment(doc, container="div", treebuilder="etree", encoding=None,
def method_decorator_metaclass(function):
class Decorated(type):
def __new__(meta, classname, bases, classDict):
for attributeName, attribute in classDict.items():
for attributeName, attribute in list(classDict.items()):
if isinstance(attribute, types.FunctionType):
attribute = function(attribute)
@@ -75,7 +75,7 @@ class HTMLParser(object):
self.errors = []
self.phases = dict([(name, cls(self, self.tree)) for name, cls in
getPhases(debug).items()])
list(getPhases(debug).items())])
def _parse(self, stream, innerHTML=False, container="div",
encoding=None, parseMeta=True, useChardet=True, **kwargs):
@@ -257,7 +257,7 @@ class HTMLParser(object):
def adjustMathMLAttributes(self, token):
replacements = {"definitionurl": "definitionURL"}
for k, v in replacements.items():
for k, v in list(replacements.items()):
if k in token["data"]:
token["data"][v] = token["data"][k]
del token["data"][k]
@@ -336,7 +336,7 @@ class HTMLParser(object):
def adjustForeignAttributes(self, token):
replacements = adjustForeignAttributesMap
for originalName in token["data"].keys():
for originalName in list(token["data"].keys()):
if originalName in replacements:
foreignName = replacements[originalName]
token["data"][foreignName] = token["data"][originalName]
@@ -411,7 +411,7 @@ def getPhases(debug):
def log(function):
"""Logger that records which phase processes each token"""
type_names = dict((value, key) for key, value in
constants.tokenTypes.items())
list(constants.tokenTypes.items()))
def wrapped(self, *args, **kwargs):
if function.__name__.startswith("process") and len(args) > 0:
@@ -472,7 +472,7 @@ def getPhases(debug):
self.parser.parseError("non-html-root")
# XXX Need a check here to see if the first start tag token emitted is
# this token... If it's not, invoke self.parser.parseError().
for attr, value in token["data"].items():
for attr, value in list(token["data"].items()):
if attr not in self.tree.openElements[0].attributes:
self.tree.openElements[0].attributes[attr] = value
self.parser.firstStartTag = False
@@ -1009,7 +1009,7 @@ def getPhases(debug):
assert self.parser.innerHTML
else:
self.parser.framesetOK = False
for attr, value in token["data"].items():
for attr, value in list(token["data"].items()):
if attr not in self.tree.openElements[1].attributes:
self.tree.openElements[1].attributes[attr] = value
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
import re
import warnings
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
import codecs
@@ -565,7 +565,7 @@ class EncodingBytes(bytes):
raise TypeError
return self[p:p + 1]
def next(self):
def __next__(self):
# Py2 compat
return self.__next__()
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
import re
from xml.sax.saxutils import escape, unescape
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from .. import treewalkers
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
import gettext
@@ -232,7 +232,7 @@ class HTMLSerializer(object):
in_cdata = True
elif in_cdata:
self.serializeError(_("Unexpected child element of a CDATA element"))
for (attr_namespace, attr_name), attr_value in token["data"].items():
for (attr_namespace, attr_name), attr_value in list(token["data"].items()):
# TODO: Add namespace support here
k = attr_name
v = attr_value
@@ -1,7 +1,7 @@
from __future__ import absolute_import, division, unicode_literals
try:
chr = unichr # flake8: noqa
chr = chr # flake8: noqa
except NameError:
pass
@@ -1,11 +1,11 @@
from __future__ import absolute_import, division, unicode_literals
from xml.sax.xmlreader import AttributesNSImpl
from ..constants import adjustForeignAttributes, unadjustForeignAttributes
prefix_mapping = {}
for prefix, localName, namespace in adjustForeignAttributes.values():
for prefix, localName, namespace in list(adjustForeignAttributes.values()):
if prefix is not None:
prefix_mapping[prefix] = namespace
@@ -13,7 +13,7 @@ for prefix, localName, namespace in adjustForeignAttributes.values():
def to_sax(walker, handler):
"""Call SAX-like content handler based on treewalker walker"""
handler.startDocument()
for prefix, namespace in prefix_mapping.items():
for prefix, namespace in list(prefix_mapping.items()):
handler.startPrefixMapping(prefix, namespace)
for token in walker:
@@ -39,6 +39,6 @@ def to_sax(walker, handler):
else:
assert False, "Unknown token type"
for prefix, namespace in prefix_mapping.items():
for prefix, namespace in list(prefix_mapping.items()):
handler.endPrefixMapping(prefix)
handler.endDocument()
@@ -26,7 +26,7 @@ returns a string containing Node and its children serialized according
to the format used in the unittests
"""
from __future__ import absolute_import, division, unicode_literals
from ..utils import default_etree
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
from ..constants import scopingElements, tableInsertModeElements, namespaces
@@ -42,7 +42,7 @@ class Node(object):
def __str__(self):
attributesStr = " ".join(["%s=\"%s\"" % (name, value)
for name, value in
self.attributes.items()])
list(self.attributes.items())])
if attributesStr:
return "<%s %s>" % (self.name, attributesStr)
else:
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from xml.dom import minidom, Node
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
import re
@@ -63,7 +63,7 @@ def getETreeBuilder(ElementTreeImplementation, fullTree=False):
# XXX - there may be a better way to do this...
for key in list(self._element.attrib.keys()):
del self._element.attrib[key]
for key, value in attributes.items():
for key, value in list(attributes.items()):
if isinstance(key, tuple):
name = "{%s}%s" % (key[2], key[1])
else:
@@ -126,7 +126,7 @@ def getETreeBuilder(ElementTreeImplementation, fullTree=False):
def cloneNode(self):
element = type(self)(self.name, self.namespace)
for name, value in self.attributes.items():
for name, value in list(self.attributes.items()):
element.attributes[name] = value
return element
@@ -230,7 +230,7 @@ def getETreeBuilder(ElementTreeImplementation, fullTree=False):
if hasattr(element, "attrib"):
attributes = []
for name, value in element.attrib.items():
for name, value in list(element.attrib.items()):
nsmatch = tag_regexp.match(name)
if nsmatch is not None:
ns, name = nsmatch.groups()
@@ -290,7 +290,7 @@ def getETreeBuilder(ElementTreeImplementation, fullTree=False):
else:
attr = " ".join(["%s=\"%s\"" % (
filter.fromXmlName(name), value)
for name, value in element.attrib.items()])
for name, value in list(element.attrib.items())])
rv.append("<%s %s>" % (element.tag, attr))
if element.text:
rv.append(element.text)
@@ -9,7 +9,7 @@ Docypes with no name
When any of these things occur, we emit a DataLossWarning
"""
from __future__ import absolute_import, division, unicode_literals
import warnings
import re
@@ -105,7 +105,7 @@ def testSerializer(element):
if hasattr(element, "attrib"):
attributes = []
for name, value in element.attrib.items():
for name, value in list(element.attrib.items()):
nsmatch = tag_regexp.match(name)
if nsmatch is not None:
ns, name = nsmatch.groups()
@@ -158,7 +158,7 @@ def tostring(element):
rv.append("<%s>" % (element.tag,))
else:
attr = " ".join(["%s=\"%s\"" % (name, value)
for name, value in element.attrib.items()])
for name, value in list(element.attrib.items())])
rv.append("<%s %s>" % (element.tag, attr))
if element.text:
rv.append(element.text)
@@ -196,7 +196,7 @@ class TreeBuilder(_base.TreeBuilder):
def __init__(self, element, value={}):
self._element = element
dict.__init__(self, value)
for key, value in self.items():
for key, value in list(self.items()):
if isinstance(key, tuple):
name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1]))
else:
@@ -8,7 +8,7 @@ implements a 'serialize' method taking a tree as sole argument and
returning an iterator generating tokens.
"""
from __future__ import absolute_import, division, unicode_literals
import sys
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type, string_types
import gettext
@@ -52,7 +52,7 @@ class TreeWalker(object):
assert all((namespace is None or isinstance(namespace, string_types)) and
isinstance(name, string_types) and
isinstance(value, string_types)
for (namespace, name), value in attrs.items())
for (namespace, name), value in list(attrs.items()))
yield {"type": "EmptyTag", "name": to_text(name, False),
"namespace": to_text(namespace),
@@ -66,14 +66,14 @@ class TreeWalker(object):
assert all((namespace is None or isinstance(namespace, string_types)) and
isinstance(name, string_types) and
isinstance(value, string_types)
for (namespace, name), value in attrs.items())
for (namespace, name), value in list(attrs.items()))
return {"type": "StartTag",
"name": text_type(name),
"namespace": to_text(namespace),
"data": dict(((to_text(namespace, False), to_text(name)),
to_text(value, False))
for (namespace, name), value in attrs.items())}
for (namespace, name), value in list(attrs.items()))}
def endTag(self, namespace, name):
assert namespace is None or isinstance(namespace, string_types), type(namespace)
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from xml.dom import Node
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
try:
from collections import OrderedDict
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from genshi.core import QName
from genshi.core import START, END, XML_NAMESPACE, DOCTYPE, TEXT
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
from lxml import etree
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \
COMMENT, IGNORABLE_WHITESPACE, CHARACTERS
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from .py import Trie as PyTrie
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from collections import Mapping
@@ -7,7 +7,7 @@ class Trie(Mapping):
"""Abstract base class for tries"""
def keys(self, prefix=None):
keys = super().keys()
keys = list(super().keys())
if prefix is None:
return set(keys)
@@ -16,7 +16,7 @@ class Trie(Mapping):
return set([x for x in keys if x.startswith(prefix)])
def has_keys_with_prefix(self, prefix):
for key in self.keys():
for key in list(self.keys()):
if key.startswith(prefix):
return True
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from datrie import Trie as DATrie
from pip._vendor.six import text_type
@@ -9,14 +9,14 @@ from ._base import Trie as ABCTrie
class Trie(ABCTrie):
def __init__(self, data):
chars = set()
for key in data.keys():
for key in list(data.keys()):
if not isinstance(key, text_type):
raise TypeError("All keys must be strings")
for char in key:
chars.add(char)
self._data = DATrie("".join(chars))
for key, value in data.items():
for key, value in list(data.items()):
self._data[key] = value
def __contains__(self, key):
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
from bisect import bisect_left
@@ -8,7 +8,7 @@ from ._base import Trie as ABCTrie
class Trie(ABCTrie):
def __init__(self, data):
if not all(isinstance(x, text_type) for x in data.keys()):
if not all(isinstance(x, text_type) for x in list(data.keys())):
raise TypeError("All keys must be strings")
self._data = data
@@ -1,4 +1,4 @@
from __future__ import absolute_import, division, unicode_literals
from types import ModuleType
@@ -32,7 +32,7 @@ import platform
from pkgutil import get_importer
try:
from urlparse import urlparse, urlunparse
from urllib.parse import urlparse, urlunparse
except ImportError:
from urllib.parse import urlparse, urlunparse
@@ -41,11 +41,11 @@ try:
except NameError:
from sets import ImmutableSet as frozenset
try:
basestring
next = lambda o: o.next()
from cStringIO import StringIO as BytesIO
str
next = lambda o: o.__next__()
from io import StringIO as BytesIO
except NameError:
basestring = str
str = str
from io import BytesIO
def execfile(fn, globs=None, locs=None):
if globs is None:
@@ -96,13 +96,13 @@ def _declare_state(vartype, **kw):
def __getstate__():
state = {}
g = globals()
for k, v in _state_vars.items():
for k, v in list(_state_vars.items()):
state[k] = g['_sget_'+v](g[k])
return state
def __setstate__(state):
g = globals()
for k, v in state.items():
for k, v in list(state.items()):
g['_sset_'+_state_vars[k]](k, g[k], v)
return state
@@ -340,7 +340,7 @@ run_main = run_script # backward compatibility
def get_distribution(dist):
"""Return a current distribution object for a Requirement or string"""
if isinstance(dist,basestring): dist = Requirement.parse(dist)
if isinstance(dist,str): dist = Requirement.parse(dist)
if isinstance(dist,Requirement): dist = get_provider(dist)
if not isinstance(dist,Distribution):
raise TypeError("Expected string, Requirement, or Distribution", dist)
@@ -514,7 +514,7 @@ class WorkingSet(object):
for dist in self:
entries = dist.get_entry_map(group)
if name is None:
for ep in entries.values():
for ep in list(entries.values()):
yield ep
elif name in entries:
yield entries[name]
@@ -871,7 +871,7 @@ class Environment(object):
def __iter__(self):
"""Yield the unique project names of the available distributions"""
for key in self._distmap.keys():
for key in list(self._distmap.keys()):
if self[key]: yield key
def __iadd__(self, other):
@@ -1281,7 +1281,7 @@ class MarkerEvaluation(object):
# markerlib implements Metadata 1.2 (PEP 345) environment markers.
# Translate the variables to Metadata 2.0 (PEP 426).
env = _markerlib.default_environment()
for key in env.keys():
for key in list(env.keys()):
new_key = key.replace('.', '_')
env[new_key] = env.pop(key)
try:
@@ -1391,7 +1391,7 @@ class NullProvider:
script_filename = self._fn(self.egg_info,script)
namespace['__file__'] = script_filename
if os.path.exists(script_filename):
execfile(script_filename, namespace, namespace)
exec(compile(open(script_filename, "rb").read(), script_filename, 'exec'), namespace, namespace)
else:
from linecache import cache
cache[script_filename] = (
@@ -1980,7 +1980,7 @@ def _set_parent_ns(packageName):
def yield_lines(strs):
"""Yield non-empty/non-comment lines of a ``basestring`` or sequence"""
if isinstance(strs,basestring):
if isinstance(strs,str):
for s in strs.splitlines():
s = s.strip()
if s and not s.startswith('#'): # skip blank lines/comments
@@ -2148,7 +2148,7 @@ class EntryPoint(object):
def parse_map(cls, data, dist=None):
"""Parse a map of entry point groups"""
if isinstance(data,dict):
data = data.items()
data = list(data.items())
else:
data = split_sections(data)
maps = {}
@@ -2641,7 +2641,7 @@ class Requirement:
if isinstance(item,Distribution):
if item.key != self.key: return False
if self.index: item = item.parsed_version # only get if we need it
elif isinstance(item,basestring):
elif isinstance(item,str):
item = parse_version(item)
last = None
compare = lambda a, b: (a > b) - (a < b) # -1, 0, 1
@@ -14,7 +14,7 @@ from .models import Response
from .packages.urllib3.poolmanager import PoolManager, proxy_from_url
from .packages.urllib3.response import HTTPResponse
from .packages.urllib3.util import Timeout as TimeoutSauce
from .compat import urlparse, basestring, urldefrag, unquote
from .compat import urlparse, str, urldefrag, unquote
from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,
prepend_scheme_if_needed, get_auth_from_url)
from .structures import CaseInsensitiveDict
@@ -95,7 +95,7 @@ class HTTPAdapter(BaseAdapter):
self.proxy_manager = {}
self.config = {}
for attr, value in state.items():
for attr, value in list(state.items()):
setattr(self, attr, value)
self.init_poolmanager(self._pool_connections, self._pool_maxsize,
@@ -149,7 +149,7 @@ class HTTPAdapter(BaseAdapter):
conn.ca_certs = None
if cert:
if not isinstance(cert, basestring):
if not isinstance(cert, str):
conn.cert_file = cert[0]
conn.key_file = cert[1]
else:
@@ -339,7 +339,7 @@ class HTTPAdapter(BaseAdapter):
url,
skip_accept_encoding=True)
for header, value in request.headers.items():
for header, value in list(request.headers.items()):
low_conn.putheader(header, value)
low_conn.endheaders()
@@ -21,4 +21,4 @@ def where():
return os.path.join(os.path.dirname(__file__), 'cacert.pem')
if __name__ == '__main__':
print(where())
print((where()))
@@ -83,20 +83,21 @@ except ImportError:
# ---------
if is_py2:
from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
from urllib.parse import quote, unquote, quote_plus, unquote_plus, urlencode
from urllib.request import getproxies
from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
from urllib2 import parse_http_list
import cookielib
from Cookie import Morsel
from StringIO import StringIO
import http.cookiejar
from http.cookies import Morsel
from io import StringIO
from .packages.urllib3.packages.ordered_dict import OrderedDict
from httplib import IncompleteRead
from http.client import IncompleteRead
builtin_str = str
bytes = str
str = unicode
basestring = basestring
numeric_types = (int, long, float)
str = str
str = str
numeric_types = (int, int, float)
elif is_py3:
@@ -111,5 +112,5 @@ elif is_py3:
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
str = (str, bytes)
numeric_types = (int, float)
@@ -207,7 +207,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
def keys(self):
"""Dict-like keys() that returns a list of names of cookies from the jar.
See values() and items()."""
return list(self.iterkeys())
return list(self.keys())
def itervalues(self):
"""Dict-like itervalues() that returns an iterator of values of cookies from the jar.
@@ -218,7 +218,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
def values(self):
"""Dict-like values() that returns a list of values of cookies from the jar.
See keys() and items()."""
return list(self.itervalues())
return list(self.values())
def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples from the jar.
@@ -230,7 +230,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):
"""Dict-like items() that returns a list of name-value tuples from the jar.
See keys() and values(). Allows client-code to call "dict(RequestsCookieJar)
and get a vanilla python dict of key value pairs."""
return list(self.iteritems())
return list(self.items())
def list_domains(self):
"""Utility method to list all the domains in the jar."""
@@ -29,7 +29,7 @@ from .utils import (
iter_slices, guess_json_utf, super_len, to_native_string)
from .compat import (
cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,
is_py2, chardet, json, builtin_str, basestring, IncompleteRead)
is_py2, chardet, json, builtin_str, str, IncompleteRead)
from .status_codes import codes
#: The set of HTTP status codes that indicate an automatically
@@ -83,7 +83,7 @@ class RequestEncodingMixin(object):
elif hasattr(data, '__iter__'):
result = []
for k, vs in to_key_val_list(data):
if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
if isinstance(vs, str) or not hasattr(vs, '__iter__'):
vs = [vs]
for v in vs:
if v is not None:
@@ -105,7 +105,7 @@ class RequestEncodingMixin(object):
"""
if (not files):
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
elif isinstance(data, str):
raise ValueError("Data must not be a string.")
new_fields = []
@@ -113,7 +113,7 @@ class RequestEncodingMixin(object):
files = to_key_val_list(files or {})
for field, val in fields:
if isinstance(val, basestring) or not hasattr(val, '__iter__'):
if isinstance(val, str) or not hasattr(val, '__iter__'):
val = [val]
for v in val:
if v is not None:
@@ -325,7 +325,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
"""Prepares the given HTTP URL."""
#: Accept objects that have string representations.
try:
url = unicode(url)
url = str(url)
except NameError:
# We're on Python 3.
url = str(url)
@@ -391,7 +391,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
"""Prepares the given HTTP headers."""
if headers:
self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in list(headers.items()))
else:
self.headers = CaseInsensitiveDict()
@@ -408,7 +408,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
is_stream = all([
hasattr(data, '__iter__'),
not isinstance(data, (basestring, list, tuple, dict))
not isinstance(data, (str, list, tuple, dict))
])
try:
@@ -568,7 +568,7 @@ class Response(object):
)
def __setstate__(self, state):
for name, value in state.items():
for name, value in list(state.items()):
setattr(self, name, value)
# pickled objects do not have .raw
@@ -582,7 +582,7 @@ class Response(object):
"""Returns true if :attr:`status_code` is 'OK'."""
return self.ok
def __nonzero__(self):
def __bool__(self):
"""Returns true if :attr:`status_code` is 'OK'."""
return self.ok
@@ -1,3 +1,3 @@
from __future__ import absolute_import
from . import urllib3
@@ -20,7 +20,7 @@ from sys import version_info
def detect(aBuf):
if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or
if ((version_info < (3, 0) and isinstance(aBuf, str)) or
(version_info >= (3, 0) and not isinstance(aBuf, bytes))):
raise ValueError('Expected a bytes object, not a unicode object')
@@ -35,11 +35,11 @@ def description_of(file, name='stdin'):
def main():
if len(argv) <= 1:
print(description_of(stdin))
print((description_of(stdin)))
else:
for path in argv[1:]:
with open(path, 'rb') as f:
print(description_of(f, path))
print((description_of(f, path)))
if __name__ == '__main__':
@@ -22,7 +22,7 @@ import sys
if sys.version_info < (3, 0):
base_str = (str, unicode)
base_str = (str, str)
else:
base_str = (bytes, str)
@@ -101,7 +101,7 @@ class RecentlyUsedContainer(MutableMapping):
def keys(self):
with self.lock:
return self._container.keys()
return list(self._container.keys())
class HTTPHeaderDict(MutableMapping):
@@ -202,4 +202,4 @@ class HTTPHeaderDict(MutableMapping):
yield headers[0][0]
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, dict(self.items()))
return '%s(%r)' % (self.__class__.__name__, dict(list(self.items())))
@@ -11,7 +11,7 @@ from socket import timeout as SocketTimeout
try: # Python 3
from http.client import HTTPConnection as _HTTPConnection, HTTPException
except ImportError:
from httplib import HTTPConnection as _HTTPConnection, HTTPException
from http.client import HTTPConnection as _HTTPConnection, HTTPException
class DummyConnection(object):
"Used to detect a failed ConnectionCls import."
@@ -27,7 +27,7 @@ try: # Compiled with SSL?
try: # Python 3
from http.client import HTTPSConnection as _HTTPSConnection
except ImportError:
from httplib import HTTPSConnection as _HTTPSConnection
from http.client import HTTPSConnection as _HTTPSConnection
import ssl
BaseSSLError = ssl.SSLError
@@ -14,8 +14,8 @@ import socket
try: # Python 3
from queue import LifoQueue, Empty, Full
except ImportError:
from Queue import LifoQueue, Empty, Full
import Queue as _ # Platform-specific: Windows
from queue import LifoQueue, Empty, Full
import queue as _ # Platform-specific: Windows
from .exceptions import (
@@ -160,7 +160,7 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
self.proxy_headers = _proxy_headers or {}
# Fill the queue up so that doing get() on it will block properly
for _ in xrange(maxsize):
for _ in range(maxsize):
self.pool.put(None)
# These are mostly for testing and debugging purposes.
@@ -13,7 +13,7 @@ Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
try:
from http.client import HTTPSConnection
except ImportError:
from httplib import HTTPSConnection
from http.client import HTTPSConnection
from logging import getLogger
from ntlm import ntlm
@@ -54,7 +54,7 @@ from pyasn1.type import univ, constraint
from socket import _fileobject, timeout
import ssl
import select
from cStringIO import StringIO
from io import StringIO
from .. import connection
from .. import util
@@ -131,7 +131,7 @@ class RequestField(object):
parts = []
iterable = header_parts
if isinstance(header_parts, dict):
iterable = header_parts.items()
iterable = list(header_parts.items())
for name, value in iterable:
if value:
@@ -150,7 +150,7 @@ class RequestField(object):
if self.headers.get(sort_key, False):
lines.append('%s: %s' % (sort_key, self.headers[sort_key]))
for header_name, header_value in self.headers.items():
for header_name, header_value in list(self.headers.items()):
if header_name not in sort_keys:
if header_value:
lines.append('%s: %s' % (header_name, header_value))
@@ -1,4 +1,4 @@
from __future__ import absolute_import
from . import ssl_match_hostname
@@ -4,9 +4,9 @@
# http://code.activestate.com/recipes/576693/
try:
from thread import get_ident as _get_ident
from _thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
from _dummy_thread import get_ident as _get_ident
try:
from _abcoll import KeysView, ValuesView, ItemsView
@@ -80,7 +80,7 @@ class OrderedDict(dict):
def clear(self):
'od.clear() -> None. Remove all items from od.'
try:
for node in self.__map.itervalues():
for node in self.__map.values():
del node[:]
root = self.__root
root[:] = [root, root, None]
@@ -163,12 +163,12 @@ class OrderedDict(dict):
for key in other:
self[key] = other[key]
elif hasattr(other, 'keys'):
for key in other.keys():
for key in list(other.keys()):
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
for key, value in list(kwds.items()):
self[key] = value
__update = update # let subclasses override update without breaking __init__
@@ -204,7 +204,7 @@ class OrderedDict(dict):
try:
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
finally:
del _repr_running[call_key]
@@ -239,7 +239,7 @@ class OrderedDict(dict):
'''
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return len(self)==len(other) and list(self.items()) == list(other.items())
return dict.__eq__(self, other)
def __ne__(self, other):
@@ -39,10 +39,10 @@ if PY3:
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
string_types = str,
integer_types = (int, int)
class_types = (type, type)
text_type = str
binary_type = str
if sys.platform.startswith("java"):
@@ -228,7 +228,7 @@ try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.next()
return it.__next__()
next = advance_iterator
@@ -242,11 +242,11 @@ if PY3:
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
else:
def get_unbound_function(unbound):
return unbound.im_func
return unbound.__func__
class Iterator(object):
def next(self):
def __next__(self):
return type(self).__next__(self)
callable = callable
@@ -291,10 +291,10 @@ else:
def b(s):
return s
def u(s):
return unicode(s, "unicode_escape")
return str(s, "unicode_escape")
int2byte = chr
import StringIO
StringIO = BytesIO = StringIO.StringIO
import io
StringIO = BytesIO = io.StringIO
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
@@ -338,19 +338,19 @@ else:
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
if not isinstance(data, str):
data = str(data)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, unicode):
if isinstance(sep, str):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, unicode):
if isinstance(end, str):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
@@ -358,12 +358,12 @@ else:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, unicode):
if isinstance(arg, str):
want_unicode = True
break
if want_unicode:
newline = unicode("\n")
space = unicode(" ")
newline = str("\n")
space = str(" ")
else:
newline = "\n"
space = " "
@@ -9,7 +9,7 @@ import logging
try: # Python 3
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
from urllib.parse import urljoin
from ._collections import RecentlyUsedContainer
from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
@@ -7,7 +7,7 @@
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from urllib.parse import urlencode
from .filepost import encode_multipart_formdata
@@ -11,7 +11,7 @@ import io
from ._collections import HTTPHeaderDict
from .exceptions import DecodeError
from .packages.six import string_types as basestring, binary_type
from .packages.six import string_types as str, binary_type
from .util import is_fp_closed
@@ -91,7 +91,7 @@ class HTTPResponse(io.IOBase):
self.decode_content = decode_content
self._decoder = None
self._body = body if body and isinstance(body, basestring) else None
self._body = body if body and isinstance(body, str) else None
self._fp = None
self._original_response = original_response
self._fp_bytes_read = 0
@@ -60,11 +60,11 @@ def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
merged_setting.update(to_key_val_list(request_setting))
# Remove keys that are set to None.
for (k, v) in request_setting.items():
for (k, v) in list(request_setting.items()):
if v is None:
del merged_setting[k]
merged_setting = dict((k, v) for (k, v) in merged_setting.items() if v is not None)
merged_setting = dict((k, v) for (k, v) in list(merged_setting.items()) if v is not None)
return merged_setting
@@ -427,7 +427,7 @@ class Session(SessionRedirectMixin):
if self.trust_env:
# Set environment's proxies.
env_proxies = get_environ_proxies(url) or {}
for (k, v) in env_proxies.items():
for (k, v) in list(env_proxies.items()):
proxies.setdefault(k, v)
# Look for configuration.
@@ -599,7 +599,7 @@ class Session(SessionRedirectMixin):
def get_adapter(self, url):
"""Returns the appropriate connnection adapter for the given URL."""
for (prefix, adapter) in self.adapters.items():
for (prefix, adapter) in list(self.adapters.items()):
if url.lower().startswith(prefix):
return adapter
@@ -609,7 +609,7 @@ class Session(SessionRedirectMixin):
def close(self):
"""Closes all adapters and as such the session"""
for v in self.adapters.values():
for v in list(self.adapters.values()):
v.close()
def mount(self, prefix, adapter):
@@ -627,7 +627,7 @@ class Session(SessionRedirectMixin):
return dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
def __setstate__(self, state):
for attr, value in state.items():
for attr, value in list(state.items()):
setattr(self, attr, value)
@@ -80,7 +80,7 @@ class CaseInsensitiveDict(collections.MutableMapping):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values())
return (casedkey for casedkey, mappedvalue in list(self._store.values()))
def __len__(self):
return len(self._store)
@@ -90,7 +90,7 @@ class CaseInsensitiveDict(collections.MutableMapping):
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
in list(self._store.items())
)
def __eq__(self, other):
@@ -103,10 +103,10 @@ class CaseInsensitiveDict(collections.MutableMapping):
# Copy is required
def copy(self):
return CaseInsensitiveDict(self._store.values())
return CaseInsensitiveDict(list(self._store.values()))
def __repr__(self):
return str(dict(self.items()))
return str(dict(list(self.items())))
class LookupDict(dict):
"""Dictionary lookup object."""
@@ -40,7 +40,7 @@ def dict_to_sequence(d):
"""Returns an internal sequence dictionary update."""
if hasattr(d, 'items'):
d = d.items()
d = list(d.items())
return d
@@ -161,7 +161,7 @@ def to_key_val_list(value):
raise ValueError('cannot encode objects that are not 2-tuples')
if isinstance(value, collections.Mapping):
value = value.items()
value = list(value.items())
return list(value)
@@ -41,10 +41,10 @@ if PY3:
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
string_types = str,
integer_types = (int, int)
class_types = (type, type)
text_type = str
binary_type = str
if sys.platform.startswith("java"):
@@ -442,7 +442,7 @@ try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.next()
return it.__next__()
next = advance_iterator
@@ -462,14 +462,14 @@ if PY3:
Iterator = object
else:
def get_unbound_function(unbound):
return unbound.im_func
return unbound.__func__
def create_bound_method(func, obj):
return types.MethodType(func, obj, obj.__class__)
class Iterator(object):
def next(self):
def __next__(self):
return type(self).__next__(self)
callable = callable
@@ -507,7 +507,7 @@ if PY3:
return s.encode("latin-1")
def u(s):
return s
unichr = chr
chr = chr
if sys.version_info[1] <= 1:
def int2byte(i):
return bytes((i,))
@@ -525,8 +525,8 @@ else:
return s
# Workaround for standalone backslash
def u(s):
return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
unichr = unichr
return str(s.replace(r'\\', r'\\\\'), "unicode_escape")
chr = chr
int2byte = chr
def byte2int(bs):
return ord(bs[0])
@@ -534,8 +534,8 @@ else:
return ord(buf[i])
def iterbytes(buf):
return (ord(byte) for byte in buf)
import StringIO
StringIO = BytesIO = StringIO.StringIO
import io
StringIO = BytesIO = io.StringIO
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
@@ -576,11 +576,11 @@ if print_ is None:
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
if not isinstance(data, str):
data = str(data)
# If the file has an encoding, encode unicode with it.
if (isinstance(fp, file) and
isinstance(data, unicode) and
isinstance(data, str) and
fp.encoding is not None):
errors = getattr(fp, "errors", None)
if errors is None:
@@ -590,13 +590,13 @@ if print_ is None:
want_unicode = False
sep = kwargs.pop("sep", None)
if sep is not None:
if isinstance(sep, unicode):
if isinstance(sep, str):
want_unicode = True
elif not isinstance(sep, str):
raise TypeError("sep must be None or a string")
end = kwargs.pop("end", None)
if end is not None:
if isinstance(end, unicode):
if isinstance(end, str):
want_unicode = True
elif not isinstance(end, str):
raise TypeError("end must be None or a string")
@@ -604,12 +604,12 @@ if print_ is None:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
for arg in args:
if isinstance(arg, unicode):
if isinstance(arg, str):
want_unicode = True
break
if want_unicode:
newline = unicode("\n")
space = unicode(" ")
newline = str("\n")
space = str(" ")
else:
newline = "\n"
space = " "
@@ -62,17 +62,17 @@ if sys.version_info >= (3,):
string_types = (str,)
raw_input = input
else:
from cStringIO import StringIO
from urllib2 import URLError, HTTPError
from Queue import Queue, Empty
from urllib import url2pathname, urlretrieve, pathname2url
from io import StringIO
from urllib.error import URLError, HTTPError
from queue import Queue, Empty
from urllib.request import url2pathname, urlretrieve, pathname2url
from email import Message as emailmessage
import urllib
import urllib2
import urlparse
import ConfigParser
import xmlrpclib
import httplib
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import urllib.parse
import configparser
import xmlrpc.client
import http.client
def b(s):
return s
@@ -88,7 +88,7 @@ else:
return result or default_value
bytes = str
string_types = (basestring,)
string_types = (str,)
reduce = reduce
cmp = cmp
raw_input = raw_input
@@ -148,7 +148,7 @@ class ConfigOptionParser(CustomOptionParser):
return option.check_value(key, val)
except optparse.OptionValueError:
e = sys.exc_info()[1]
print("An error occurred during configuration: %s" % e)
print(("An error occurred during configuration: %s" % e))
sys.exit(3)
def update_defaults(self, defaults):
@@ -163,7 +163,7 @@ class ConfigOptionParser(CustomOptionParser):
# 2. environmental variables
config.update(self.normalize_keys(self.get_environ_vars()))
# Then set the options with those values
for key, val in config.items():
for key, val in list(config.items()):
option = self.get_option(key)
if option is not None:
# ignore empty values
@@ -200,7 +200,7 @@ class ConfigOptionParser(CustomOptionParser):
def get_environ_vars(self, prefix='PIP_'):
"""Returns a generator with all environmental vars with prefix PIP_"""
for key, val in os.environ.items():
for key, val in list(os.environ.items()):
if key.startswith(prefix):
yield (key.replace(prefix, '').lower(), val)
@@ -54,7 +54,7 @@ def get_summaries(ignore_hidden=True, ordered=True):
if ordered:
cmditems = _sort_commands(commands, commands_order)
else:
cmditems = commands.items()
cmditems = list(commands.items())
for name, command_class in cmditems:
if ignore_hidden and command_class.hidden:
@@ -67,7 +67,7 @@ def get_similar_commands(name):
"""Command name auto-correct."""
from difflib import get_close_matches
close_commands = get_close_matches(name, commands.keys())
close_commands = get_close_matches(name, list(commands.keys()))
if close_commands:
guess = close_commands[0]
@@ -85,4 +85,4 @@ def _sort_commands(cmddict, order):
# unordered items should come last
return 0xff
return sorted(cmddict.items(), key=keyfn)
return sorted(list(cmddict.items()), key=keyfn)
@@ -50,10 +50,10 @@ class CompletionCommand(Command):
def run(self, options, args):
"""Prints the completion code of the given shell"""
shells = COMPLETION_SCRIPTS.keys()
shells = list(COMPLETION_SCRIPTS.keys())
shell_options = ['--' + shell for shell in sorted(shells)]
if options.shell in shells:
script = COMPLETION_SCRIPTS.get(options.shell, '')
print(BASE_COMPLETION % {'script': script, 'shell': options.shell})
print((BASE_COMPLETION % {'script': script, 'shell': options.shell}))
else:
sys.stderr.write('ERROR: You must pass %s\n' % ' or '.join(shell_options))
@@ -110,5 +110,5 @@ class FreezeCommand(Command):
f.write(str(installations[line_req.name]))
del installations[line_req.name]
f.write('## The following requirements were added by pip --freeze:\n')
for installation in sorted(installations.values(), key=lambda x: x.name):
for installation in sorted(list(installations.values()), key=lambda x: x.name):
f.write(str(installation))
@@ -11,6 +11,7 @@ from pip.exceptions import CommandError
from pip.status_codes import NO_MATCHES_FOUND
from pip._vendor import pkg_resources
from distutils.version import StrictVersion, LooseVersion
from functools import reduce
class SearchCommand(Command):
@@ -70,7 +71,7 @@ def transform_hits(hits):
if score is None:
score = 0
if name not in packages.keys():
if name not in list(packages.keys()):
packages[name] = {'name': name, 'summary': summary, 'versions': [version], 'score': score}
else:
packages[name]['versions'].append(version)
@@ -81,7 +82,7 @@ def transform_hits(hits):
packages[name]['score'] = score
# each record has a unique name now, so we will convert the dict into a list sorted by score
package_list = sorted(packages.values(), key=lambda x: x['score'], reverse=True)
package_list = sorted(list(packages.values()), key=lambda x: x['score'], reverse=True)
return package_list
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import sys
@@ -114,7 +114,7 @@ class MultiDomainBasicAuth(AuthBase):
parsed = urlparse.urlparse(resp.url)
# Prompt the user for a new username and password
username = raw_input("User for %s: " % parsed.netloc)
username = input("User for %s: " % parsed.netloc)
password = getpass.getpass("Password: ")
# Store the new username and password to use for future requests
@@ -257,7 +257,7 @@ def get_file_content(url, comes_from=None, session=None):
match = _url_slash_drive_re.match(path)
if match:
path = match.group(1) + ':' + path.split('|', 1)[1]
path = urllib.unquote(path)
path = urllib.parse.unquote(path)
if path.startswith('/'):
path = '/' + path.lstrip('/')
url = path
@@ -300,7 +300,7 @@ def url_to_path(url):
assert url.startswith('file:'), (
"You can only turn file: urls into filenames (not %r)" % url)
path = url[len('file:'):].lstrip('/')
path = urllib.unquote(path)
path = urllib.parse.unquote(path)
if _url_drive_re.match(path):
path = path[0] + ':' + path[2:]
else:
@@ -320,7 +320,7 @@ def path_to_url(path):
path = os.path.normpath(os.path.abspath(path))
drive, path = os.path.splitdrive(path)
filepath = path.split(os.path.sep)
url = '/'.join([urllib.quote(part) for part in filepath])
url = '/'.join([urllib.parse.quote(part) for part in filepath])
if not drive:
url = url.lstrip('/')
return 'file:///' + drive + url
@@ -485,7 +485,7 @@ def unpack_http_url(link, location, download_cache, download_dir=None,
# If a download cache is specified, is the file cached there?
if download_cache:
cache_file = os.path.join(download_cache,
urllib.quote(target_url, ''))
urllib.parse.quote(target_url, ''))
cache_content_type_file = cache_file + '.content-type'
already_cached = (
os.path.exists(cache_file) and
@@ -82,8 +82,8 @@ def _get_build_prefix():
msg = "The temporary folder for building (%s) is either not owned by you, or is a symlink." \
% path
print (msg)
print("pip will not work until the temporary folder is " + \
"either deleted or is a real directory owned by your user account.")
print(("pip will not work until the temporary folder is " + \
"either deleted or is a real directory owned by your user account."))
raise pip.exceptions.InstallationError(msg)
return path
+10 -10
View File
@@ -257,7 +257,7 @@ class InstallRequirement(object):
def url_name(self):
if self.req is None:
return None
return urllib.quote(self.req.unsafe_name)
return urllib.parse.quote(self.req.unsafe_name)
@property
def setup_py(self):
@@ -931,7 +931,7 @@ class Requirements(object):
return self._dict[key]
def __repr__(self):
values = ['%s: %s' % (repr(k), repr(self[k])) for k in self.keys()]
values = ['%s: %s' % (repr(k), repr(self[k])) for k in list(self.keys())]
return 'Requirements({%s})' % ', '.join(values)
@@ -967,7 +967,7 @@ class RequirementSet(object):
self.wheel_download_dir = wheel_download_dir
def __str__(self):
reqs = [req for req in self.requirements.values()
reqs = [req for req in list(self.requirements.values())
if not req.comes_from]
reqs.sort(key=lambda req: req.name.lower())
return ' '.join([str(req.req) for req in reqs])
@@ -1003,7 +1003,7 @@ class RequirementSet(object):
@property
def has_editables(self):
if any(req.editable for req in self.requirements.values()):
if any(req.editable for req in list(self.requirements.values())):
return True
if any(req.editable for req in self.unnamed_requirements):
return True
@@ -1031,7 +1031,7 @@ class RequirementSet(object):
raise KeyError("No project with the name %r" % project_name)
def uninstall(self, auto_confirm=False):
for req in self.requirements.values():
for req in list(self.requirements.values()):
req.uninstall(auto_confirm=auto_confirm)
req.commit_uninstall()
@@ -1379,7 +1379,7 @@ class RequirementSet(object):
def install(self, install_options, global_options=(), *args, **kwargs):
"""Install everything in this set (after having downloaded and unpacked the packages)"""
to_install = [r for r in self.requirements.values()
to_install = [r for r in list(self.requirements.values())
if not r.satisfied_by]
# DISTRIBUTE TO SETUPTOOLS UPGRADE HACK (1 of 3 parts)
@@ -1505,11 +1505,11 @@ class RequirementSet(object):
def bundle_requirements(self):
parts = [self.BUNDLE_HEADER]
for req in [req for req in self.requirements.values()
for req in [req for req in list(self.requirements.values())
if not req.comes_from]:
parts.append('%s==%s\n' % (req.name, req.installed_version))
parts.append('# These packages were installed to satisfy the above requirements:\n')
for req in [req for req in self.requirements.values()
for req in [req for req in list(self.requirements.values())
if req.comes_from]:
parts.append('%s==%s\n' % (req.name, req.installed_version))
## FIXME: should we do something with self.unnamed_requirements?
@@ -1834,7 +1834,7 @@ class UninstallPathSet(object):
logger.info('Removing file or directory %s' % path)
self._moved_paths.append(path)
renames(path, new_path)
for pth in self.pth.values():
for pth in list(self.pth.values()):
pth.remove()
logger.notify('Successfully uninstalled %s' % self.dist.project_name)
@@ -1923,7 +1923,7 @@ class FakeFile(object):
try:
return next(self._gen)
except NameError:
return self._gen.next()
return next(self._gen)
except StopIteration:
return ''
@@ -129,11 +129,11 @@ def ask(message, options):
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception('No input was expected ($PIP_NO_INPUT set); question: %s' % message)
response = raw_input(message)
response = input(message)
response = response.strip().lower()
if response not in options:
print('Your response (%r) was not one of the expected responses: %s' % (
response, ', '.join(options)))
print(('Your response (%r) was not one of the expected responses: %s' % (
response, ', '.join(options))))
else:
return response
@@ -52,7 +52,7 @@ class VcsSupport(object):
def unregister(self, cls=None, name=None):
if name in self._registry:
del self._registry[name]
elif cls in self._registry.values():
elif cls in list(self._registry.values()):
del self._registry[cls.name]
else:
logger.warn('Cannot unregister because no class or name given')
@@ -62,7 +62,7 @@ class VcsSupport(object):
Return the name of the version control backend if found at given
location, e.g. vcs.get_backend_name('/path/to/vcs/checkout')
"""
for vc_type in self._registry.values():
for vc_type in list(self._registry.values()):
path = os.path.join(location, vc_type.dirname)
if os.path.exists(path):
return vc_type.name
@@ -141,7 +141,7 @@ class VersionControl(object):
"""
Normalize a URL for comparison by unquoting it and removing any trailing slash.
"""
return urllib.unquote(url).rstrip('/')
return urllib.parse.unquote(url).rstrip('/')
def compare_urls(self, url1, url2):
"""
@@ -158,7 +158,7 @@ class Git(VersionControl):
refs = self.get_refs(location)
# refs maps names to commit hashes; we need the inverse
# if multiple names map to a single commit, this arbitrarily picks one
names_by_commit = dict((commit, ref) for ref, commit in refs.items())
names_by_commit = dict((commit, ref) for ref, commit in list(refs.items()))
if current_rev in names_by_commit:
# It's a tag
@@ -1,7 +1,7 @@
"""
Support for installing and building the "wheel" binary package format.
"""
from __future__ import with_statement
import compileall
import csv
@@ -45,9 +45,9 @@ def rehash(path, algo='sha256', blocksize=1<<20):
return (digest, length)
try:
unicode
str
def binary(s):
if isinstance(s, unicode):
if isinstance(s, str):
return s.encode('ascii')
return s
except NameError:
@@ -194,7 +194,7 @@ def move_wheel_files(name, req, wheeldir, user=False, home=None, root=None,
info_dir.append(destsubdir)
for f in files:
# Skip unwanted files
if filter and filter(f):
if filter and list(filter(f)):
continue
srcfile = os.path.join(dir, f)
destfile = os.path.join(dest, basedir, f)
@@ -346,9 +346,9 @@ if __name__ == '__main__':
# Generate the console and GUI entry points specified in the wheel
if len(console) > 0:
generated.extend(maker.make_multiple(['%s = %s' % kv for kv in console.items()]))
generated.extend(maker.make_multiple(['%s = %s' % kv for kv in list(console.items())]))
if len(gui) > 0:
generated.extend(maker.make_multiple(['%s = %s' % kv for kv in gui.items()], {'gui': True}))
generated.extend(maker.make_multiple(['%s = %s' % kv for kv in list(gui.items())], {'gui': True}))
record = os.path.join(info_dir[0], 'RECORD')
temp_record = os.path.join(info_dir[0], 'RECORD.pip')
@@ -532,7 +532,7 @@ class WheelBuilder(object):
#unpack and constructs req set
self.requirement_set.prepare_files(self.finder)
reqset = self.requirement_set.requirements.values()
reqset = list(self.requirement_set.requirements.values())
buildset = [req for req in reqset if not req.is_wheel]
+1 -1
View File
@@ -47,7 +47,7 @@ def enforce_good_python():
goodpython = lookfor_good_python27()
if not goodpython:
raise DistutilsError,'No good python identified on your system'
raise DistutilsError('No good python identified on your system')
goodpython=goodpython[0]
@@ -54,7 +54,7 @@ def get_a_virtualenv_module(pip=None):
log.debug('temp install dir : %s' % tmpdir)
if ok!=0:
raise DistutilsError, "I cannot install a virtualenv package"
raise DistutilsError("I cannot install a virtualenv package")
f, filename, description = imp.find_module('virtualenv', [tmpdir])
@@ -109,7 +109,7 @@ def serenity_virtualenv(envname,package,version,minversion=PIP_MINVERSION,pip=No
# The virtualenv already exist but it is not ok
#
if not ok:
raise DistutilsError, "A virtualenv %s already exists but not with the required python"
raise DistutilsError("A virtualenv %s already exists but not with the required python")
else:
ok = False

Some files were not shown because too many files have changed in this diff Show More