Skip to content

Commit 680b5df

Browse files
vsajipvbabiy
authored andcommitted
Port to Python3
1 parent 6c82a1b commit 680b5df

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+699
-393
lines changed

LICENSE.txt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
Copyright (c) 2008-2010 Ian Bicking and Contributors
2-
Copyright (c) 2011 The virtualenv developers
1+
Copyright (c) 2008-2011 The pip developers (see AUTHORS.txt file)
32

43
Permission is hereby granted, free of charge, to any person obtaining
54
a copy of this software and associated documentation files (the

docs/news.txt

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,7 @@ tip (unreleased)
2828

2929
* Fixed issue #204 - rmtree undefined in mercurial.py. Thanks Kelsey Hightower
3030

31-
* Fixed bug in Git vcs backend that would break during reinstallation.
3231

33-
* Fixed bug in Mercurial vcs backend related to pip freeze and branch/tag resolution.
34-
35-
* Fixed bug in version string parsing related to the suffix "-dev".
3632

3733
0.8.2
3834
-----

pip/__init__.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from pip.exceptions import InstallationError
1313
from pip.log import logger
1414
from pip.util import get_installed_distributions
15-
from pip.backwardcompat import walk_packages
15+
from pip.backwardcompat import u, walk_packages
1616

1717

1818
def autocomplete():
@@ -53,30 +53,30 @@ def autocomplete():
5353
# if there are no dists installed, fall back to option completion
5454
if installed:
5555
for dist in installed:
56-
print dist
56+
print(dist)
5757
sys.exit(1)
5858
subcommand = command_dict.get(subcommand_name)
5959
options += [(opt.get_opt_string(), opt.nargs)
6060
for opt in subcommand.parser.option_list
6161
if opt.help != optparse.SUPPRESS_HELP]
6262
# filter out previously specified options from available options
6363
prev_opts = [x.split('=')[0] for x in cwords[1:cword-1]]
64-
options = filter(lambda (x, v): x not in prev_opts, options)
64+
options = [(x, v) for (x, v) in options if x not in prev_opts]
6565
# filter options by current input
6666
options = [(k, v) for k, v in options if k.startswith(current)]
6767
for option in options:
6868
opt_label = option[0]
6969
# append '=' to options which require args
7070
if option[1]:
7171
opt_label += '='
72-
print opt_label
72+
print(opt_label)
7373
else:
7474
# show options of main parser only when necessary
7575
if current.startswith('-') or current.startswith('--'):
7676
subcommands += [opt.get_opt_string()
7777
for opt in parser.option_list
7878
if opt.help != optparse.SUPPRESS_HELP]
79-
print ' '.join(filter(lambda x: x.startswith(current), subcommands))
79+
print(' '.join([x for x in subcommands if x.startswith(current)]))
8080
sys.exit(1)
8181

8282

@@ -213,15 +213,16 @@ def call_subprocess(cmd, show_stdout=True,
213213
proc = subprocess.Popen(
214214
cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
215215
cwd=cwd, env=env)
216-
except Exception, e:
216+
except Exception:
217+
e = sys.exc_info()[1]
217218
logger.fatal(
218219
"Error %s while executing command %s" % (e, command_desc))
219220
raise
220221
all_output = []
221222
if stdout is not None:
222223
stdout = proc.stdout
223224
while 1:
224-
line = stdout.readline()
225+
line = u(stdout.readline())
225226
if not line:
226227
break
227228
line = line.rstrip()

pip/_pkgutil.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import imp
99
import os.path
1010
from types import ModuleType
11+
from pip.backwardcompat import string_types
1112

1213
__all__ = [
1314
'get_importer', 'iter_importers', 'get_loader', 'find_loader',
@@ -324,7 +325,7 @@ def get_filename(self, fullname=None):
324325
from zipimport import zipimporter
325326

326327
def iter_zipimport_modules(importer, prefix=''):
327-
dirlist = zipimport._zip_directory_cache[importer.archive].keys()
328+
dirlist = list(zipimport._zip_directory_cache[importer.archive].keys())
328329
dirlist.sort()
329330
_prefix = importer.prefix
330331
plen = len(_prefix)
@@ -523,7 +524,7 @@ def extend_path(path, name):
523524
path = path[:] # Start with a copy of the existing path
524525

525526
for dir in sys.path:
526-
if not isinstance(dir, basestring) or not os.path.isdir(dir):
527+
if not isinstance(dir, string_types) or not os.path.isdir(dir):
527528
continue
528529
subdir = os.path.join(dir, pname)
529530
# XXX This may still add duplicate entries to path on
@@ -537,7 +538,8 @@ def extend_path(path, name):
537538
if os.path.isfile(pkgfile):
538539
try:
539540
f = open(pkgfile)
540-
except IOError, msg:
541+
except IOError:
542+
msg = sys.exc_info()[1]
541543
sys.stderr.write("Can't open %s: %s\n" %
542544
(pkgfile, msg))
543545
else:

pip/backwardcompat.py

Lines changed: 56 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Stuff that isn't in some old versions of Python"""
1+
"""Stuff that differs in different Python versions"""
22

33
import sys
44
import os
@@ -9,7 +9,9 @@
99
try:
1010
WindowsError = WindowsError
1111
except NameError:
12-
WindowsError = None
12+
class NeverUsedException(Exception):
13+
"""this exception should never be raised"""
14+
WindowsError = NeverUsedException
1315
try:
1416
from hashlib import md5
1517
except ImportError:
@@ -20,7 +22,7 @@
2022
from pkgutil import walk_packages
2123
except ImportError:
2224
# let's fall back as long as we can
23-
from _pkgutil import walk_packages
25+
from pip._pkgutil import walk_packages
2426

2527
try:
2628
any = any
@@ -32,6 +34,56 @@ def any(seq):
3234
return True
3335
return False
3436

37+
if sys.version_info >= (3,):
38+
from io import StringIO
39+
from functools import reduce
40+
from urllib.error import URLError, HTTPError
41+
from queue import Queue, Empty
42+
from urllib.request import url2pathname
43+
from urllib.request import urlretrieve
44+
from email import message as emailmessage
45+
import urllib.parse as urllib
46+
import urllib.request as urllib2
47+
import configparser as ConfigParser
48+
import xmlrpc.client as xmlrpclib
49+
import urllib.parse as urlparse
50+
import http.client as httplib
51+
def cmp(a, b):
52+
return (a > b) - (a < b)
53+
def b(s):
54+
return s.encode('utf-8')
55+
def u(s):
56+
return s.decode('utf-8')
57+
string_types = (str,)
58+
raw_input = input
59+
else:
60+
from cStringIO import StringIO
61+
from urllib2 import URLError, HTTPError
62+
from Queue import Queue, Empty
63+
from urllib import url2pathname, urlretrieve
64+
from email import Message as emailmessage
65+
import urllib
66+
import urllib2
67+
import urlparse
68+
import ConfigParser
69+
import xmlrpclib
70+
import httplib
71+
def b(s):
72+
return s
73+
def u(s):
74+
return s
75+
string_types = (basestring,)
76+
reduce = reduce
77+
cmp = cmp
78+
raw_input = raw_input
79+
80+
try:
81+
from email.parser import FeedParser
82+
except ImportError:
83+
# python lesser than 2.5
84+
from email.FeedParser import FeedParser
85+
86+
from distutils.sysconfig import get_python_lib, get_python_version
3587

3688
def copytree(src, dst):
3789
if sys.version_info < (2, 5):
@@ -47,7 +99,7 @@ def copytree(src, dst):
4799
def product(*args, **kwds):
48100
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
49101
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
50-
pools = map(tuple, args) * kwds.get('repeat', 1)
102+
pools = list(map(tuple, args)) * kwds.get('repeat', 1)
51103
result = [[]]
52104
for pool in pools:
53105
result = [x+[y] for x in result for y in pool]

pip/basecommand.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Base Command class, and related routines"""
22

3-
from cStringIO import StringIO
43
import os
54
import socket
65
import sys
@@ -13,7 +12,7 @@
1312
from pip.download import urlopen
1413
from pip.exceptions import BadCommand, InstallationError, UninstallationError
1514
from pip.venv import restart_in_venv
16-
from pip.backwardcompat import walk_packages
15+
from pip.backwardcompat import StringIO, urllib, urllib2, walk_packages
1716

1817
__all__ = ['command_dict', 'Command', 'load_all_commands',
1918
'load_command', 'command_names']
@@ -125,11 +124,13 @@ def main(self, complete_args, args, initial_options):
125124
exit = 0
126125
try:
127126
self.run(options, args)
128-
except (InstallationError, UninstallationError), e:
127+
except (InstallationError, UninstallationError):
128+
e = sys.exc_info()[1]
129129
logger.fatal(str(e))
130130
logger.info('Exception information:\n%s' % format_exc())
131131
exit = 1
132-
except BadCommand, e:
132+
except BadCommand:
133+
e = sys.exc_info()[1]
133134
logger.fatal(str(e))
134135
logger.info('Exception information:\n%s' % format_exc())
135136
exit = 1
@@ -174,8 +175,8 @@ def open_logfile(filename, mode='a'):
174175

175176
log_fp = open(filename, mode)
176177
if exists:
177-
print >> log_fp, '-'*60
178-
print >> log_fp, '%s run on %s' % (sys.argv[0], time.strftime('%c'))
178+
log_fp.write('%s\n' % ('-'*60))
179+
log_fp.write('%s run on %s\n' % (sys.argv[0], time.strftime('%c')))
179180
return log_fp
180181

181182

pip/baseparser.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
import sys
44
import optparse
55
import pkg_resources
6-
import ConfigParser
76
import os
87
from distutils.util import strtobool
8+
from pip.backwardcompat import ConfigParser, string_types
99
from pip.locations import default_config_file, default_log_file
1010

1111

@@ -50,7 +50,7 @@ def update_defaults(self, defaults):
5050
# 2. environmental variables
5151
config.update(dict(self.get_environ_vars()))
5252
# Then set the options with those values
53-
for key, val in config.iteritems():
53+
for key, val in config.items():
5454
key = key.replace('_', '-')
5555
if not key.startswith('--'):
5656
key = '--%s' % key # only prefer long opts
@@ -68,8 +68,9 @@ def update_defaults(self, defaults):
6868
val = strtobool(val)
6969
try:
7070
val = option.convert_value(key, val)
71-
except optparse.OptionValueError, e:
72-
print ("An error occured during configuration: %s" % e)
71+
except optparse.OptionValueError:
72+
e = sys.exc_info()[1]
73+
print("An error occured during configuration: %s" % e)
7374
sys.exit(3)
7475
defaults[option.dest] = val
7576
return defaults
@@ -82,7 +83,7 @@ def get_config_section(self, name):
8283

8384
def get_environ_vars(self, prefix='PIP_'):
8485
"""Returns a generator with all environmental vars with prefix PIP_"""
85-
for key, val in os.environ.iteritems():
86+
for key, val in os.environ.items():
8687
if key.startswith(prefix):
8788
yield (key.replace(prefix, '').lower(), val)
8889

@@ -96,7 +97,7 @@ def get_default_values(self):
9697
defaults = self.update_defaults(self.defaults.copy()) # ours
9798
for option in self._get_all_options():
9899
default = defaults.get(option.dest)
99-
if isinstance(default, basestring):
100+
if isinstance(default, string_types):
100101
opt_str = option.get_opt_string()
101102
defaults[option.dest] = option.check_value(opt_str, default)
102103
return optparse.Values(defaults)

pip/commands/completion.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def run(self, options, args):
5353
shell_options = ['--'+shell for shell in sorted(shells)]
5454
if options.shell in shells:
5555
script = COMPLETION_SCRIPTS.get(options.shell, '')
56-
print BASE_COMPLETION % {'script': script, 'shell': options.shell}
56+
print(BASE_COMPLETION % {'script': script, 'shell': options.shell})
5757
else:
5858
sys.stderr.write('ERROR: You must pass %s\n' % ' or '.join(shell_options))
5959

pip/commands/help.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,13 @@ def run(self, options, args):
1919
command.parser.print_help()
2020
return
2121
parser.print_help()
22-
print
23-
print 'Commands available:'
22+
print('\nCommands available:')
2423
commands = list(set(command_dict.values()))
2524
commands.sort(key=lambda x: x.name)
2625
for command in commands:
2726
if command.hidden:
2827
continue
29-
print ' %s: %s' % (command.name, command.summary)
28+
print(' %s: %s' % (command.name, command.summary))
3029

3130

3231
HelpCommand()

pip/commands/search.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import sys
2-
import xmlrpclib
32
import textwrap
43
import pkg_resources
54
import pip.download
65
from pip.basecommand import Command
76
from pip.util import get_terminal_size
87
from pip.log import logger
8+
from pip.backwardcompat import xmlrpclib, reduce, cmp
99
from distutils.version import StrictVersion, LooseVersion
1010

1111

@@ -69,7 +69,7 @@ def transform_hits(hits):
6969
packages[name]['score'] = score
7070

7171
# each record has a unique name now, so we will convert the dict into a list sorted by score
72-
package_list = sorted(packages.values(), lambda x, y: cmp(y['score'], x['score']))
72+
package_list = sorted(packages.values(), key=lambda x: x['score'], reverse=True)
7373
return package_list
7474

7575

0 commit comments

Comments
 (0)