repo
stringclasses
32 values
instance_id
stringlengths
13
37
base_commit
stringlengths
40
40
patch
stringlengths
1
1.89M
test_patch
stringclasses
1 value
problem_statement
stringlengths
304
69k
hints_text
stringlengths
0
246k
created_at
stringlengths
20
20
version
stringclasses
1 value
FAIL_TO_PASS
stringclasses
1 value
PASS_TO_PASS
stringclasses
1 value
environment_setup_commit
stringclasses
1 value
traceback
stringlengths
64
23.4k
__index_level_0__
int64
29
19k
pypa/pip
pypa__pip-2331
28d7dce042d39c264e8ed13e1f0399978fe03f5c
diff --git a/pip/utils/outdated.py b/pip/utils/outdated.py --- a/pip/utils/outdated.py +++ b/pip/utils/outdated.py @@ -73,8 +73,11 @@ def save(self, pypi_version, current_time): # Attempt to write out our version check file with lockfile.LockFile(self.statefile_path): - with open(self.statefile_path) as statefile: - state = json.load(statefile) + if os.path.exists(self.statefile_path): + with open(self.statefile_path) as statefile: + state = json.load(statefile) + else: + state = {} state[sys.prefix] = { "last_check": current_time.strftime(SELFCHECK_DATE_FMT),
pip self check fails to handle first run correctly The following will be seen on any non-virtualenv invocation of pip with --verbose: ``` Traceback (most recent call last): File ".../lib/python2.7/site-packages/pip/utils/outdated.py", line 115, in pip_version_check state.save(pypi_version, current_time) File ".../lib/python2.7/site-packages/pip/utils/outdated.py", line 62, in save with open(self.statefile_path) as statefile: IOError: [Errno 2] No such file or directory: '.../Library/Caches/pip/selfcheck.json' ``` Because on the first run of the outdated.py code, that file doesn't exist. PR incoming.
2015-01-06T05:14:53Z
[]
[]
Traceback (most recent call last): File ".../lib/python2.7/site-packages/pip/utils/outdated.py", line 115, in pip_version_check state.save(pypi_version, current_time) File ".../lib/python2.7/site-packages/pip/utils/outdated.py", line 62, in save with open(self.statefile_path) as statefile: IOError: [Errno 2] No such file or directory: '.../Library/Caches/pip/selfcheck.json'
17,205
pypa/pip
pypa__pip-2469
1e1650133ed8d90f291dccd6545294b379480d4c
diff --git a/pip/_vendor/requests/__init__.py b/pip/_vendor/requests/__init__.py --- a/pip/_vendor/requests/__init__.py +++ b/pip/_vendor/requests/__init__.py @@ -36,17 +36,17 @@ The other HTTP methods are supported - see `requests.api`. Full documentation is at <http://python-requests.org>. -:copyright: (c) 2014 by Kenneth Reitz. +:copyright: (c) 2015 by Kenneth Reitz. :license: Apache 2.0, see LICENSE for more details. """ __title__ = 'requests' -__version__ = '2.5.1' -__build__ = 0x020501 +__version__ = '2.5.3' +__build__ = 0x020503 __author__ = 'Kenneth Reitz' __license__ = 'Apache 2.0' -__copyright__ = 'Copyright 2014 Kenneth Reitz' +__copyright__ = 'Copyright 2015 Kenneth Reitz' # Attempt to enable urllib3's SNI support, if possible try: diff --git a/pip/_vendor/requests/auth.py b/pip/_vendor/requests/auth.py --- a/pip/_vendor/requests/auth.py +++ b/pip/_vendor/requests/auth.py @@ -124,13 +124,15 @@ def sha_utf8(x): s += os.urandom(8) cnonce = (hashlib.sha1(s).hexdigest()[:16]) - noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, HA2) if _algorithm == 'MD5-SESS': HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce)) if qop is None: respdig = KD(HA1, "%s:%s" % (nonce, HA2)) elif qop == 'auth' or 'auth' in qop.split(','): + noncebit = "%s:%s:%s:%s:%s" % ( + nonce, ncvalue, cnonce, 'auth', HA2 + ) respdig = KD(HA1, noncebit) else: # XXX handle auth-int. diff --git a/pip/_vendor/requests/compat.py b/pip/_vendor/requests/compat.py --- a/pip/_vendor/requests/compat.py +++ b/pip/_vendor/requests/compat.py @@ -21,58 +21,6 @@ #: Python 3.x? is_py3 = (_ver[0] == 3) -#: Python 3.0.x -is_py30 = (is_py3 and _ver[1] == 0) - -#: Python 3.1.x -is_py31 = (is_py3 and _ver[1] == 1) - -#: Python 3.2.x -is_py32 = (is_py3 and _ver[1] == 2) - -#: Python 3.3.x -is_py33 = (is_py3 and _ver[1] == 3) - -#: Python 3.4.x -is_py34 = (is_py3 and _ver[1] == 4) - -#: Python 2.7.x -is_py27 = (is_py2 and _ver[1] == 7) - -#: Python 2.6.x -is_py26 = (is_py2 and _ver[1] == 6) - -#: Python 2.5.x -is_py25 = (is_py2 and _ver[1] == 5) - -#: Python 2.4.x -is_py24 = (is_py2 and _ver[1] == 4) # I'm assuming this is not by choice. - - -# --------- -# Platforms -# --------- - - -# Syntax sugar. -_ver = sys.version.lower() - -is_pypy = ('pypy' in _ver) -is_jython = ('jython' in _ver) -is_ironpython = ('iron' in _ver) - -# Assume CPython, if nothing else. -is_cpython = not any((is_pypy, is_jython, is_ironpython)) - -# Windows-based system. -is_windows = 'win32' in str(sys.platform).lower() - -# Standard Linux 2+ system. -is_linux = ('linux' in str(sys.platform).lower()) -is_osx = ('darwin' in str(sys.platform).lower()) -is_hpux = ('hpux' in str(sys.platform).lower()) # Complete guess. -is_solaris = ('solar==' in str(sys.platform).lower()) # Complete guess. - try: import simplejson as json except (ImportError, SyntaxError): @@ -99,7 +47,6 @@ basestring = basestring numeric_types = (int, long, float) - elif is_py3: from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag from urllib.request import parse_http_list, getproxies, proxy_bypass diff --git a/pip/_vendor/requests/cookies.py b/pip/_vendor/requests/cookies.py --- a/pip/_vendor/requests/cookies.py +++ b/pip/_vendor/requests/cookies.py @@ -157,26 +157,28 @@ class CookieConflictError(RuntimeError): class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): - """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface. + """Compatibility class; is a cookielib.CookieJar, but exposes a dict + interface. This is the CookieJar we create by default for requests and sessions that don't specify one, since some clients may expect response.cookies and session.cookies to support dict operations. - Don't use the dict interface internally; it's just for compatibility with - with external client code. All `requests` code should work out of the box - with externally provided instances of CookieJar, e.g., LWPCookieJar and - FileCookieJar. - - Caution: dictionary operations that are normally O(1) may be O(n). + Requests does not use the dict interface internally; it's just for + compatibility with external client code. All requests code should work + out of the box with externally provided instances of ``CookieJar``, e.g. + ``LWPCookieJar`` and ``FileCookieJar``. Unlike a regular CookieJar, this class is pickleable. - """ + .. warning:: dictionary operations that are normally O(1) may be O(n). + """ def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over - multiple domains. Caution: operation is O(n), not O(1).""" + multiple domains. + + .. warning:: operation is O(n), not O(1).""" try: return self._find_no_duplicates(name, domain, path) except KeyError: @@ -199,37 +201,38 @@ def set(self, name, value, **kwargs): return c def iterkeys(self): - """Dict-like iterkeys() that returns an iterator of names of cookies from the jar. - See itervalues() and iteritems().""" + """Dict-like iterkeys() that returns an iterator of names of cookies + from the jar. See itervalues() and iteritems().""" for cookie in iter(self): yield cookie.name def keys(self): - """Dict-like keys() that returns a list of names of cookies from the jar. - See values() and items().""" + """Dict-like keys() that returns a list of names of cookies from the + jar. See values() and items().""" return list(self.iterkeys()) def itervalues(self): - """Dict-like itervalues() that returns an iterator of values of cookies from the jar. - See iterkeys() and iteritems().""" + """Dict-like itervalues() that returns an iterator of values of cookies + from the jar. See iterkeys() and iteritems().""" for cookie in iter(self): yield cookie.value def values(self): - """Dict-like values() that returns a list of values of cookies from the jar. - See keys() and items().""" + """Dict-like values() that returns a list of values of cookies from the + jar. See keys() and items().""" return list(self.itervalues()) def iteritems(self): - """Dict-like iteritems() that returns an iterator of name-value tuples from the jar. - See iterkeys() and itervalues().""" + """Dict-like iteritems() that returns an iterator of name-value tuples + from the jar. See iterkeys() and itervalues().""" for cookie in iter(self): yield cookie.name, cookie.value def items(self): - """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.""" + """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()) def list_domains(self): @@ -259,8 +262,9 @@ def multiple_domains(self): return False # there is only one domain in jar def get_dict(self, domain=None, path=None): - """Takes as an argument an optional domain and path and returns a plain old - Python dict of name-value pairs of cookies that meet the requirements.""" + """Takes as an argument an optional domain and path and returns a plain + old Python dict of name-value pairs of cookies that meet the + requirements.""" dictionary = {} for cookie in iter(self): if (domain is None or cookie.domain == domain) and (path is None @@ -269,21 +273,24 @@ def get_dict(self, domain=None, path=None): return dictionary def __getitem__(self, name): - """Dict-like __getitem__() for compatibility with client code. Throws exception - if there are more than one cookie with name. In that case, use the more - explicit get() method instead. Caution: operation is O(n), not O(1).""" + """Dict-like __getitem__() for compatibility with client code. Throws + exception if there are more than one cookie with name. In that case, + use the more explicit get() method instead. + + .. warning:: operation is O(n), not O(1).""" return self._find_no_duplicates(name) def __setitem__(self, name, value): - """Dict-like __setitem__ for compatibility with client code. Throws exception - if there is already a cookie of that name in the jar. In that case, use the more - explicit set() method instead.""" + """Dict-like __setitem__ for compatibility with client code. Throws + exception if there is already a cookie of that name in the jar. In that + case, use the more explicit set() method instead.""" self.set(name, value) def __delitem__(self, name): - """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name().""" + """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s + ``remove_cookie_by_name()``.""" remove_cookie_by_name(self, name) def set_cookie(self, cookie, *args, **kwargs): @@ -300,10 +307,11 @@ def update(self, other): super(RequestsCookieJar, self).update(other) def _find(self, name, domain=None, path=None): - """Requests uses this method internally to get cookie values. Takes as args name - and optional domain and path. Returns a cookie.value. If there are conflicting cookies, - _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown - if there are conflicting cookies.""" + """Requests uses this method internally to get cookie values. Takes as + args name and optional domain and path. Returns a cookie.value. If + there are conflicting cookies, _find arbitrarily chooses one. See + _find_no_duplicates if you want an exception thrown if there are + conflicting cookies.""" for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: @@ -313,10 +321,11 @@ def _find(self, name, domain=None, path=None): raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) def _find_no_duplicates(self, name, domain=None, path=None): - """__get_item__ and get call _find_no_duplicates -- never used in Requests internally. - Takes as args name and optional domain and path. Returns a cookie.value. - Throws KeyError if cookie is not found and CookieConflictError if there are - multiple cookies that match name and optionally domain and path.""" + """Both ``__get_item__`` and ``get`` call this function: it's never + used elsewhere in Requests. Takes as args name and optional domain and + path. Returns a cookie.value. Throws KeyError if cookie is not found + and CookieConflictError if there are multiple cookies that match name + and optionally domain and path.""" toReturn = None for cookie in iter(self): if cookie.name == name: @@ -440,7 +449,7 @@ def merge_cookies(cookiejar, cookies): """ if not isinstance(cookiejar, cookielib.CookieJar): raise ValueError('You can only merge into CookieJar') - + if isinstance(cookies, dict): cookiejar = cookiejar_from_dict( cookies, cookiejar=cookiejar, overwrite=False) diff --git a/pip/_vendor/requests/packages/__init__.py b/pip/_vendor/requests/packages/__init__.py --- a/pip/_vendor/requests/packages/__init__.py +++ b/pip/_vendor/requests/packages/__init__.py @@ -1,3 +1,95 @@ +""" +Copyright (c) Donald Stufft, pip, and individual contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +""" from __future__ import absolute_import -from . import urllib3 +import sys + + +class VendorAlias(object): + + def __init__(self): + self._vendor_name = __name__ + self._vendor_pkg = self._vendor_name + "." + + def find_module(self, fullname, path=None): + if fullname.startswith(self._vendor_pkg): + return self + + def load_module(self, name): + # Ensure that this only works for the vendored name + if not name.startswith(self._vendor_pkg): + raise ImportError( + "Cannot import %s, must be a subpackage of '%s'." % ( + name, self._vendor_name, + ) + ) + + # Check to see if we already have this item in sys.modules, if we do + # then simply return that. + if name in sys.modules: + return sys.modules[name] + + # Check to see if we can import the vendor name + try: + # We do this dance here because we want to try and import this + # module without hitting a recursion error because of a bunch of + # VendorAlias instances on sys.meta_path + real_meta_path = sys.meta_path[:] + try: + sys.meta_path = [ + m for m in sys.meta_path + if not isinstance(m, VendorAlias) + ] + __import__(name) + module = sys.modules[name] + finally: + # Re-add any additions to sys.meta_path that were made while + # during the import we just did, otherwise things like + # requests.packages.urllib3.poolmanager will fail. + for m in sys.meta_path: + if m not in real_meta_path: + real_meta_path.append(m) + + # Restore sys.meta_path with any new items. + sys.meta_path = real_meta_path + except ImportError: + # We can't import the vendor name, so we'll try to import the + # "real" name. + real_name = name[len(self._vendor_pkg):] + try: + __import__(real_name) + module = sys.modules[real_name] + except ImportError: + raise ImportError("No module named '%s'" % (name,)) + + # If we've gotten here we've found the module we're looking for, either + # as part of our vendored package, or as the real name, so we'll add + # it to sys.modules as the vendored name so that we don't have to do + # the lookup again. + sys.modules[name] = module + + # Finally, return the loaded module + return module + + +sys.meta_path.append(VendorAlias()) diff --git a/pip/_vendor/requests/packages/urllib3/__init__.py b/pip/_vendor/requests/packages/urllib3/__init__.py --- a/pip/_vendor/requests/packages/urllib3/__init__.py +++ b/pip/_vendor/requests/packages/urllib3/__init__.py @@ -55,7 +55,7 @@ def add_stderr_logger(level=logging.DEBUG): del NullHandler -# Set security warning to only go off once by default. +# Set security warning to always go off by default. import warnings warnings.simplefilter('always', exceptions.SecurityWarning) diff --git a/pip/_vendor/requests/packages/urllib3/_collections.py b/pip/_vendor/requests/packages/urllib3/_collections.py --- a/pip/_vendor/requests/packages/urllib3/_collections.py +++ b/pip/_vendor/requests/packages/urllib3/_collections.py @@ -1,7 +1,7 @@ from collections import Mapping, MutableMapping try: from threading import RLock -except ImportError: # Platform-specific: No threads available +except ImportError: # Platform-specific: No threads available class RLock: def __enter__(self): pass @@ -10,16 +10,18 @@ def __exit__(self, exc_type, exc_value, traceback): pass -try: # Python 2.7+ +try: # Python 2.7+ from collections import OrderedDict except ImportError: from .packages.ordered_dict import OrderedDict -from .packages.six import iterkeys, itervalues +from .packages.six import iterkeys, itervalues, PY3 __all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict'] +MULTIPLE_HEADERS_ALLOWED = frozenset(['cookie', 'set-cookie', 'set-cookie2']) + _Null = object() @@ -97,7 +99,14 @@ def keys(self): return list(iterkeys(self._container)) -class HTTPHeaderDict(MutableMapping): +_dict_setitem = dict.__setitem__ +_dict_getitem = dict.__getitem__ +_dict_delitem = dict.__delitem__ +_dict_contains = dict.__contains__ +_dict_setdefault = dict.setdefault + + +class HTTPHeaderDict(dict): """ :param headers: An iterable of field-value pairs. Must not contain multiple field names @@ -129,25 +138,72 @@ class HTTPHeaderDict(MutableMapping): 'foo=bar, baz=quxx' >>> headers['Content-Length'] '7' - - If you want to access the raw headers with their original casing - for debugging purposes you can access the private ``._data`` attribute - which is a normal python ``dict`` that maps the case-insensitive key to a - list of tuples stored as (case-sensitive-original-name, value). Using the - structure from above as our example: - - >>> headers._data - {'set-cookie': [('Set-Cookie', 'foo=bar'), ('set-cookie', 'baz=quxx')], - 'content-length': [('content-length', '7')]} """ def __init__(self, headers=None, **kwargs): - self._data = {} - if headers is None: - headers = {} - self.update(headers, **kwargs) + dict.__init__(self) + if headers is not None: + self.extend(headers) + if kwargs: + self.extend(kwargs) - def add(self, key, value): + def __setitem__(self, key, val): + return _dict_setitem(self, key.lower(), (key, val)) + + def __getitem__(self, key): + val = _dict_getitem(self, key.lower()) + return ', '.join(val[1:]) + + def __delitem__(self, key): + return _dict_delitem(self, key.lower()) + + def __contains__(self, key): + return _dict_contains(self, key.lower()) + + def __eq__(self, other): + if not isinstance(other, Mapping) and not hasattr(other, 'keys'): + return False + if not isinstance(other, type(self)): + other = type(self)(other) + return dict((k1, self[k1]) for k1 in self) == dict((k2, other[k2]) for k2 in other) + + def __ne__(self, other): + return not self.__eq__(other) + + values = MutableMapping.values + get = MutableMapping.get + update = MutableMapping.update + + if not PY3: # Python 2 + iterkeys = MutableMapping.iterkeys + itervalues = MutableMapping.itervalues + + __marker = object() + + def pop(self, key, default=__marker): + '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value. + If key is not found, d is returned if given, otherwise KeyError is raised. + ''' + # Using the MutableMapping function directly fails due to the private marker. + # Using ordinary dict.pop would expose the internal structures. + # So let's reinvent the wheel. + try: + value = self[key] + except KeyError: + if default is self.__marker: + raise + return default + else: + del self[key] + return value + + def discard(self, key): + try: + del self[key] + except KeyError: + pass + + def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it already exists. @@ -156,43 +212,108 @@ def add(self, key, value): >>> headers['foo'] 'bar, baz' """ - self._data.setdefault(key.lower(), []).append((key, value)) + key_lower = key.lower() + new_vals = key, val + # Keep the common case aka no item present as fast as possible + vals = _dict_setdefault(self, key_lower, new_vals) + if new_vals is not vals: + # new_vals was not inserted, as there was a previous one + if isinstance(vals, list): + # If already several items got inserted, we have a list + vals.append(val) + else: + # vals should be a tuple then, i.e. only one item so far + if key_lower in MULTIPLE_HEADERS_ALLOWED: + # Need to convert the tuple to list for further extension + _dict_setitem(self, key_lower, [vals[0], vals[1], val]) + else: + _dict_setitem(self, key_lower, new_vals) + + def extend(*args, **kwargs): + """Generic import function for any type of header-like object. + Adapted version of MutableMapping.update in order to insert items + with self.add instead of self.__setitem__ + """ + if len(args) > 2: + raise TypeError("update() takes at most 2 positional " + "arguments ({} given)".format(len(args))) + elif not args: + raise TypeError("update() takes at least 1 argument (0 given)") + self = args[0] + other = args[1] if len(args) >= 2 else () + + if isinstance(other, Mapping): + for key in other: + self.add(key, other[key]) + elif hasattr(other, "keys"): + for key in other.keys(): + self.add(key, other[key]) + else: + for key, value in other: + self.add(key, value) + + for key, value in kwargs.items(): + self.add(key, value) def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" - return self[key].split(', ') if key in self else [] - - def copy(self): - h = HTTPHeaderDict() - for key in self._data: - for rawkey, value in self._data[key]: - h.add(rawkey, value) - return h - - def __eq__(self, other): - if not isinstance(other, Mapping): - return False - other = HTTPHeaderDict(other) - return dict((k1, self[k1]) for k1 in self._data) == \ - dict((k2, other[k2]) for k2 in other._data) - - def __getitem__(self, key): - values = self._data[key.lower()] - return ', '.join(value[1] for value in values) - - def __setitem__(self, key, value): - self._data[key.lower()] = [(key, value)] - - def __delitem__(self, key): - del self._data[key.lower()] - - def __len__(self): - return len(self._data) - - def __iter__(self): - for headers in itervalues(self._data): - yield headers[0][0] + try: + vals = _dict_getitem(self, key.lower()) + except KeyError: + return [] + else: + if isinstance(vals, tuple): + return [vals[1]] + else: + return vals[1:] + + # Backwards compatibility for httplib + getheaders = getlist + getallmatchingheaders = getlist + iget = getlist def __repr__(self): - return '%s(%r)' % (self.__class__.__name__, dict(self.items())) + return "%s(%s)" % (type(self).__name__, dict(self.itermerged())) + + def copy(self): + clone = type(self)() + for key in self: + val = _dict_getitem(self, key) + if isinstance(val, list): + # Don't need to convert tuples + val = list(val) + _dict_setitem(clone, key, val) + return clone + + def iteritems(self): + """Iterate over all header lines, including duplicate ones.""" + for key in self: + vals = _dict_getitem(self, key) + for val in vals[1:]: + yield vals[0], val + + def itermerged(self): + """Iterate over all headers, merging duplicate ones together.""" + for key in self: + val = _dict_getitem(self, key) + yield val[0], ', '.join(val[1:]) + + def items(self): + return list(self.iteritems()) + + @classmethod + def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2 + """Read headers from a Python 2 httplib message object.""" + ret = cls(message.items()) + # ret now contains only the last header line for each duplicate. + # Importing with all duplicates would be nice, but this would + # mean to repeat most of the raw parsing already done, when the + # message object was created. Extracting only the headers of interest + # separately, the cookies, should be faster and requires less + # extra code. + for key in duplicates: + ret.discard(key) + for val in message.getheaders(key): + ret.add(key, val) + return ret diff --git a/pip/_vendor/requests/packages/urllib3/connectionpool.py b/pip/_vendor/requests/packages/urllib3/connectionpool.py --- a/pip/_vendor/requests/packages/urllib3/connectionpool.py +++ b/pip/_vendor/requests/packages/urllib3/connectionpool.py @@ -72,6 +72,21 @@ def __str__(self): return '%s(host=%r, port=%r)' % (type(self).__name__, self.host, self.port) + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + # Return False to re-raise any potential exceptions + return False + + def close(): + """ + Close all pooled connections and disable the pool. + """ + pass + + # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252 _blocking_errnos = set([errno.EAGAIN, errno.EWOULDBLOCK]) @@ -266,6 +281,10 @@ def _validate_conn(self, conn): """ pass + def _prepare_proxy(self, conn): + # Nothing to do for HTTP connections. + pass + def _get_timeout(self, timeout): """ Helper that always returns a :class:`urllib3.util.Timeout` """ if timeout is _Default: @@ -349,7 +368,7 @@ def _make_request(self, conn, method, url, timeout=_Default, # Receive the response from the server try: - try: # Python 2.7+, use buffering of HTTP responses + try: # Python 2.7, use buffering of HTTP responses httplib_response = conn.getresponse(buffering=True) except TypeError: # Python 2.6 and older httplib_response = conn.getresponse() @@ -510,11 +529,18 @@ def urlopen(self, method, url, body=None, headers=None, retries=None, try: # Request a connection from the queue. + timeout_obj = self._get_timeout(timeout) conn = self._get_conn(timeout=pool_timeout) + conn.timeout = timeout_obj.connect_timeout + + is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None) + if is_new_proxy_conn: + self._prepare_proxy(conn) + # Make the request on the httplib connection object. httplib_response = self._make_request(conn, method, url, - timeout=timeout, + timeout=timeout_obj, body=body, headers=headers) # If we're going to release the connection in ``finally:``, then @@ -547,6 +573,14 @@ def urlopen(self, method, url, body=None, headers=None, retries=None, conn = None raise SSLError(e) + except SSLError: + # Treat SSLError separately from BaseSSLError to preserve + # traceback. + if conn: + conn.close() + conn = None + raise + except (TimeoutError, HTTPException, SocketError, ConnectionError) as e: if conn: # Discard the connection for these exceptions. It will be @@ -554,14 +588,13 @@ def urlopen(self, method, url, body=None, headers=None, retries=None, conn.close() conn = None - stacktrace = sys.exc_info()[2] if isinstance(e, SocketError) and self.proxy: e = ProxyError('Cannot connect to proxy.', e) elif isinstance(e, (SocketError, HTTPException)): e = ProtocolError('Connection aborted.', e) - retries = retries.increment(method, url, error=e, - _pool=self, _stacktrace=stacktrace) + retries = retries.increment(method, url, error=e, _pool=self, + _stacktrace=sys.exc_info()[2]) retries.sleep() # Keep track of the error for the retry warning. @@ -673,23 +706,25 @@ def _prepare_conn(self, conn): assert_fingerprint=self.assert_fingerprint) conn.ssl_version = self.ssl_version - if self.proxy is not None: - # Python 2.7+ - try: - set_tunnel = conn.set_tunnel - except AttributeError: # Platform-specific: Python 2.6 - set_tunnel = conn._set_tunnel + return conn - if sys.version_info <= (2, 6, 4) and not self.proxy_headers: # Python 2.6.4 and older - set_tunnel(self.host, self.port) - else: - set_tunnel(self.host, self.port, self.proxy_headers) + def _prepare_proxy(self, conn): + """ + Establish tunnel connection early, because otherwise httplib + would improperly set Host: header to proxy's IP:port. + """ + # Python 2.7+ + try: + set_tunnel = conn.set_tunnel + except AttributeError: # Platform-specific: Python 2.6 + set_tunnel = conn._set_tunnel - # Establish tunnel connection early, because otherwise httplib - # would improperly set Host: header to proxy's IP:port. - conn.connect() + if sys.version_info <= (2, 6, 4) and not self.proxy_headers: # Python 2.6.4 and older + set_tunnel(self.host, self.port) + else: + set_tunnel(self.host, self.port, self.proxy_headers) - return conn + conn.connect() def _new_conn(self): """ diff --git a/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py b/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py --- a/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py +++ b/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py @@ -191,6 +191,11 @@ def recv(self, *args, **kwargs): return b'' else: raise + except OpenSSL.SSL.ZeroReturnError as e: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return b'' + else: + raise except OpenSSL.SSL.WantReadError: rd, wd, ed = select.select( [self.socket], [], [], self.socket.gettimeout()) diff --git a/pip/_vendor/requests/packages/urllib3/poolmanager.py b/pip/_vendor/requests/packages/urllib3/poolmanager.py --- a/pip/_vendor/requests/packages/urllib3/poolmanager.py +++ b/pip/_vendor/requests/packages/urllib3/poolmanager.py @@ -8,7 +8,7 @@ from ._collections import RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool from .connectionpool import port_by_scheme -from .exceptions import LocationValueError +from .exceptions import LocationValueError, MaxRetryError from .request import RequestMethods from .util.url import parse_url from .util.retry import Retry @@ -64,6 +64,14 @@ def __init__(self, num_pools=10, headers=None, **connection_pool_kw): self.pools = RecentlyUsedContainer(num_pools, dispose_func=lambda p: p.close()) + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.clear() + # Return False to re-raise any potential exceptions + return False + def _new_pool(self, scheme, host, port): """ Create a new :class:`ConnectionPool` based on host, port and scheme. @@ -167,7 +175,14 @@ def urlopen(self, method, url, redirect=True, **kw): if not isinstance(retries, Retry): retries = Retry.from_int(retries, redirect=redirect) - kw['retries'] = retries.increment(method, redirect_location) + try: + retries = retries.increment(method, url, response=response, _pool=conn) + except MaxRetryError: + if retries.raise_on_redirect: + raise + return response + + kw['retries'] = retries kw['redirect'] = redirect log.info("Redirecting %s -> %s" % (url, redirect_location)) diff --git a/pip/_vendor/requests/packages/urllib3/response.py b/pip/_vendor/requests/packages/urllib3/response.py --- a/pip/_vendor/requests/packages/urllib3/response.py +++ b/pip/_vendor/requests/packages/urllib3/response.py @@ -4,12 +4,11 @@ from ._collections import HTTPHeaderDict from .exceptions import ProtocolError, DecodeError, ReadTimeoutError -from .packages.six import string_types as basestring, binary_type +from .packages.six import string_types as basestring, binary_type, PY3 from .connection import HTTPException, BaseSSLError from .util.response import is_fp_closed - class DeflateDecoder(object): def __init__(self): @@ -21,6 +20,9 @@ def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): + if not data: + return data + if not self._first_try: return self._obj.decompress(data) @@ -36,9 +38,23 @@ def decompress(self, data): self._data = None +class GzipDecoder(object): + + def __init__(self): + self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) + + def __getattr__(self, name): + return getattr(self._obj, name) + + def decompress(self, data): + if not data: + return data + return self._obj.decompress(data) + + def _get_decoder(mode): if mode == 'gzip': - return zlib.decompressobj(16 + zlib.MAX_WBITS) + return GzipDecoder() return DeflateDecoder() @@ -76,9 +92,10 @@ def __init__(self, body='', headers=None, status=0, version=0, reason=None, strict=0, preload_content=True, decode_content=True, original_response=None, pool=None, connection=None): - self.headers = HTTPHeaderDict() - if headers: - self.headers.update(headers) + if isinstance(headers, HTTPHeaderDict): + self.headers = headers + else: + self.headers = HTTPHeaderDict(headers) self.status = status self.version = version self.reason = reason @@ -202,7 +219,7 @@ def read(self, amt=None, decode_content=None, cache_content=False): except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? - if not 'read operation timed out' in str(e): # Defensive: + if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise @@ -267,14 +284,16 @@ def from_httplib(ResponseCls, r, **response_kw): Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ - - headers = HTTPHeaderDict() - for k, v in r.getheaders(): - headers.add(k, v) + headers = r.msg + if not isinstance(headers, HTTPHeaderDict): + if PY3: # Python 3 + headers = HTTPHeaderDict(headers.items()) + else: # Python 2 + headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) - return ResponseCls(body=r, + resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, @@ -282,6 +301,7 @@ def from_httplib(ResponseCls, r, **response_kw): strict=strict, original_response=r, **response_kw) + return resp # Backwards-compatibility methods for httplib.HTTPResponse def getheaders(self): diff --git a/pip/_vendor/requests/packages/urllib3/util/connection.py b/pip/_vendor/requests/packages/urllib3/util/connection.py --- a/pip/_vendor/requests/packages/urllib3/util/connection.py +++ b/pip/_vendor/requests/packages/urllib3/util/connection.py @@ -82,6 +82,7 @@ def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, err = _ if sock is not None: sock.close() + sock = None if err is not None: raise err diff --git a/pip/_vendor/requests/packages/urllib3/util/retry.py b/pip/_vendor/requests/packages/urllib3/util/retry.py --- a/pip/_vendor/requests/packages/urllib3/util/retry.py +++ b/pip/_vendor/requests/packages/urllib3/util/retry.py @@ -190,7 +190,7 @@ def _is_read_error(self, err): return isinstance(err, (ReadTimeoutError, ProtocolError)) def is_forced_retry(self, method, status_code): - """ Is this method/response retryable? (Based on method/codes whitelists) + """ Is this method/status code retryable? (Based on method/codes whitelists) """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False diff --git a/pip/_vendor/requests/packages/urllib3/util/ssl_.py b/pip/_vendor/requests/packages/urllib3/util/ssl_.py --- a/pip/_vendor/requests/packages/urllib3/util/ssl_.py +++ b/pip/_vendor/requests/packages/urllib3/util/ssl_.py @@ -1,5 +1,5 @@ from binascii import hexlify, unhexlify -from hashlib import md5, sha1 +from hashlib import md5, sha1, sha256 from ..exceptions import SSLError @@ -29,8 +29,8 @@ except ImportError: _DEFAULT_CIPHERS = ( 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' - 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:' - 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5' + 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:' + '!eNULL:!MD5' ) try: @@ -96,7 +96,8 @@ def assert_fingerprint(cert, fingerprint): # this digest. hashfunc_map = { 16: md5, - 20: sha1 + 20: sha1, + 32: sha256, } fingerprint = fingerprint.replace(':', '').lower() @@ -211,7 +212,9 @@ def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED, context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 - context.check_hostname = (context.verify_mode == ssl.CERT_REQUIRED) + # We do our own verification, including fingerprints and alternative + # hostnames. So disable it here + context.check_hostname = False return context diff --git a/pip/_vendor/requests/utils.py b/pip/_vendor/requests/utils.py --- a/pip/_vendor/requests/utils.py +++ b/pip/_vendor/requests/utils.py @@ -25,7 +25,8 @@ from . import certs from .compat import parse_http_list as _parse_list_header from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2, - builtin_str, getproxies, proxy_bypass, urlunparse) + builtin_str, getproxies, proxy_bypass, urlunparse, + basestring) from .cookies import RequestsCookieJar, cookiejar_from_dict from .structures import CaseInsensitiveDict from .exceptions import InvalidURL @@ -115,7 +116,8 @@ def get_netrc_auth(url): def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) - if name and isinstance(name, builtin_str) and name[0] != '<' and name[-1] != '>': + if (name and isinstance(name, basestring) and name[0] != '<' and + name[-1] != '>'): return os.path.basename(name) @@ -418,10 +420,18 @@ def requote_uri(uri): This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. """ - # Unquote only the unreserved characters - # Then quote only illegal characters (do not quote reserved, unreserved, - # or '%') - return quote(unquote_unreserved(uri), safe="!#$%&'()*+,/:;=?@[]~") + safe_with_percent = "!#$%&'()*+,/:;=?@[]~" + safe_without_percent = "!#$&'()*+,/:;=?@[]~" + try: + # Unquote only the unreserved characters + # Then quote only illegal characters (do not quote reserved, + # unreserved, or '%') + return quote(unquote_unreserved(uri), safe=safe_with_percent) + except InvalidURL: + # We couldn't unquote the given URI, so let's try quoting it, but + # there may be unquoted '%'s in the URI. We need to make sure they're + # properly quoted so they do not cause issues elsewhere. + return quote(uri, safe=safe_without_percent) def address_in_network(ip, net):
Python 2.7.9 change broke urllib3 on platforms where the OpenSSL library has SNI disabled This is not a bug in `pip`, but I'm reporting it here as someone using `pip` on Python 2.7.9 with an OpenSSL version that does _not_ have SNI enabled is likely to see this traceback when encountering this issue: ``` python Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/basecommand.py", line 232, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/commands/install.py", line 339, in run requirement_set.prepare_files(finder) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/req/req_set.py", line 333, in prepare_files upgrade=self.upgrade, File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/index.py", line 305, in find_requirement page = self._get_page(main_index_url, req) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/index.py", line 783, in _get_page return HTMLPage.get_page(link, req, session=self.session) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/index.py", line 872, in get_page "Cache-Control": "max-age=600", File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/sessions.py", line 473, in get return self.request('GET', url, **kwargs) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/download.py", line 365, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/sessions.py", line 461, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/sessions.py", line 573, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/cachecontrol/adapter.py", line 43, in send resp = super(CacheControlAdapter, self).send(request, **kw) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/adapters.py", line 370, in send timeout=timeout File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py", line 518, in urlopen body=body, headers=headers) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py", line 322, in _make_request self._validate_conn(conn) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py", line 727, in _validate_conn conn.connect() File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/connection.py", line 238, in connect ssl_version=resolved_ssl_version) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py", line 254, in ssl_wrap_socket return context.wrap_socket(sock) File "/usr/local/lib/python2.7/ssl.py", line 350, in wrap_socket _context=self) File "/usr/local/lib/python2.7/ssl.py", line 537, in __init__ raise ValueError("check_hostname requires server_hostname") ValueError: check_hostname requires server_hostname ``` This is an issue with `urllib3`, see shazow/urllib3#543, also noted at kennethreitz/requests#2435. By placing this here the `pip` project has a place to track status on this and redirect people that encounter the problem.
Yep, I've bumped into this as well. I nudged https://github.com/shazow/urllib3/pull/526 to get a release going, which we can then upgrade to. kennethreitz/requests#2444 has been merged and new version(s) released, any chance for an update here shortly?
2015-03-02T20:08:00Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/basecommand.py", line 232, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/commands/install.py", line 339, in run requirement_set.prepare_files(finder) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/req/req_set.py", line 333, in prepare_files upgrade=self.upgrade, File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/index.py", line 305, in find_requirement page = self._get_page(main_index_url, req) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/index.py", line 783, in _get_page return HTMLPage.get_page(link, req, session=self.session) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/index.py", line 872, in get_page "Cache-Control": "max-age=600", File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/sessions.py", line 473, in get return self.request('GET', url, **kwargs) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/download.py", line 365, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/sessions.py", line 461, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/sessions.py", line 573, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/cachecontrol/adapter.py", line 43, in send resp = super(CacheControlAdapter, self).send(request, **kw) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/adapters.py", line 370, in send timeout=timeout File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py", line 518, in urlopen body=body, headers=headers) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py", line 322, in _make_request self._validate_conn(conn) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py", line 727, in _validate_conn conn.connect() File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/connection.py", line 238, in connect ssl_version=resolved_ssl_version) File "/usr/local/lib/python2.7/site-packages/pip-6.0.7-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py", line 254, in ssl_wrap_socket return context.wrap_socket(sock) File "/usr/local/lib/python2.7/ssl.py", line 350, in wrap_socket _context=self) File "/usr/local/lib/python2.7/ssl.py", line 537, in __init__ raise ValueError("check_hostname requires server_hostname") ValueError: check_hostname requires server_hostname
17,213
pypa/pip
pypa__pip-2659
0c9af4cad94aca9b4367bd4b3b4cc855d27fdb07
diff --git a/pip/req/req_set.py b/pip/req/req_set.py --- a/pip/req/req_set.py +++ b/pip/req/req_set.py @@ -200,9 +200,7 @@ def add_requirement(self, install_req, parent_req_name=None): requirement is applicable and has just been added. """ name = install_req.name - if ((not name or not self.has_requirement(name)) and not - install_req.match_markers()): - # Only log if we haven't already got install_req from somewhere. + if not install_req.match_markers(): logger.debug("Ignore %s: markers %r don't match", install_req.name, install_req.markers) return []
Conflicts on exclusive environment markers This used to work in a `requirement.txt` file (and python 2.7): ``` Django>=1.6.10,<1.8 ; python_version != '2.6' Django>=1.6.10,<1.7 ; python_version == '2.6' ``` Simple script to reproduce: ``` from pip.download import PipSession from pip.req import RequirementSet from pip.req.req_install import InstallRequirement r27 = InstallRequirement.from_line("Django>=1.6.10,<1.8 ; python_version != '2.6'") r26 = InstallRequirement.from_line("Django>=1.6.10,<1.7 ; python_version == '2.6'") req_set = RequirementSet('', '', '', session=PipSession()) req_set.add_requirement(r27) req_set.add_requirement(r26) ``` Which produce (on python 2.7): ``` Traceback (most recent call last): File "py26_bug.py", line 10, in <module> req_set.add_requirement(r26) File "/home/xfernandez/.virtualenvs/2aa975fa9aadd974/local/lib/python2.7/site-packages/pip/req/req_set.py", line 223, in add_requirement % (install_req, self.get_requirement(name), name)) pip.exceptions.InstallationError: Double requirement given: Django<1.7,>=1.6.10 (already in Django<1.8,>=1.6.10, name='Django') ``` This comes from the fact that the environment markers are only checked for new requirements: cf https://github.com/pypa/pip/blob/develop/pip/req/req_set.py#L203-L204
2015-04-07T20:38:09Z
[]
[]
Traceback (most recent call last): File "py26_bug.py", line 10, in <module> req_set.add_requirement(r26) File "/home/xfernandez/.virtualenvs/2aa975fa9aadd974/local/lib/python2.7/site-packages/pip/req/req_set.py", line 223, in add_requirement % (install_req, self.get_requirement(name), name)) pip.exceptions.InstallationError: Double requirement given: Django<1.7,>=1.6.10 (already in Django<1.8,>=1.6.10, name='Django')
17,221
pypa/pip
pypa__pip-2856
f25aef072003abc2760293afd43b2b4a4402a5b0
diff --git a/pip/wheel.py b/pip/wheel.py --- a/pip/wheel.py +++ b/pip/wheel.py @@ -55,7 +55,7 @@ def __init__(self, cache_dir, format_control): :param format_control: A pip.index.FormatControl object to limit binaries being read from the cache. """ - self._cache_dir = os.path.expanduser(cache_dir) + self._cache_dir = os.path.expanduser(cache_dir) if cache_dir else None self._format_control = format_control def cached_wheel(self, link, package_name):
AttributeError: 'bool' object has no attribute 'startswith' ``` pip wheel pip setuptools wheel virtualenv --find-links=file:///home/ionel/stuff --no-cache-dir --wheel-dir=. --isolated Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/wheel.py", line 162, in run wheel_cache = WheelCache(options.cache_dir, options.format_control) File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 58, in __init__ self._cache_dir = os.path.expanduser(cache_dir) File "/usr/lib/python2.7/posixpath.py", line 252, in expanduser if not path.startswith('~'): AttributeError: 'bool' object has no attribute 'startswith' ``` Versions: ``` pip --version pip 7.0.2 from /usr/local/lib/python2.7/dist-packages (python 2.7) ```
If I remove `--no-cache-dir` it works fine.
2015-06-02T00:52:26Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/wheel.py", line 162, in run wheel_cache = WheelCache(options.cache_dir, options.format_control) File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 58, in __init__ self._cache_dir = os.path.expanduser(cache_dir) File "/usr/lib/python2.7/posixpath.py", line 252, in expanduser if not path.startswith('~'): AttributeError: 'bool' object has no attribute 'startswith'
17,234
pypa/pip
pypa__pip-299
48152adaad5231aa9dc9f289c1b70fb34c0e9e5e
diff --git a/pip/backwardcompat.py b/pip/backwardcompat.py --- a/pip/backwardcompat.py +++ b/pip/backwardcompat.py @@ -37,7 +37,7 @@ def any(seq): console_encoding = sys.__stdout__.encoding if sys.version_info >= (3,): - from io import StringIO + from io import StringIO, BytesIO from functools import reduce from urllib.error import URLError, HTTPError from queue import Queue, Empty @@ -91,6 +91,7 @@ def console_to_str(s): reduce = reduce cmp = cmp raw_input = raw_input + BytesIO = StringIO try: from email.parser import FeedParser diff --git a/pip/index.py b/pip/index.py --- a/pip/index.py +++ b/pip/index.py @@ -3,6 +3,7 @@ import sys import os import re +import gzip import mimetypes import threading import posixpath @@ -10,11 +11,12 @@ import random import socket import string +import zlib from pip.log import logger from pip.util import Inf from pip.util import normalize_name, splitext from pip.exceptions import DistributionNotFound -from pip.backwardcompat import (WindowsError, +from pip.backwardcompat import (WindowsError, BytesIO, Queue, httplib, urlparse, URLError, HTTPError, u, product, url2pathname) @@ -442,7 +444,15 @@ def get_page(cls, link, req, cache=None, skip_archives=True): real_url = geturl(resp) headers = resp.info() - inst = cls(u(resp.read()), real_url, headers) + contents = resp.read() + encoding = headers.get('Content-Encoding', None) + #XXX need to handle exceptions and add testing for this + if encoding is not None: + if encoding == 'gzip': + contents = gzip.GzipFile(fileobj=BytesIO(contents)).read() + if encoding == 'deflate': + contents = zlib.decompress(contents) + inst = cls(u(contents), real_url, headers) except (HTTPError, URLError, socket.timeout, socket.error, OSError, WindowsError): e = sys.exc_info()[1] desc = str(e)
Handle encoding gzip/deflate - causing python 3.x tests failing with UnicodeDecodeError There seems to be an issue here - potentially a threading issue on py3k when running the tests we get ``` Exception in thread Thread-1: Traceback (most recent call last): File "/usr/local/lib/python3.1/threading.py", line 516, in _bootstrap_inner self.run() File "/usr/local/lib/python3.1/threading.py", line 469, in run self._target(*self._args, **self._kwargs) File "/var/lib/hudson/jobs/pip_python3.1/workspace/tests/tests_cache/test_ws/.virtualenv/lib/python3.1/site-packages/pip-1.0.1-py3.1.egg/pip/index.py", line 239, in _get_queued_page page = self._get_page(location, req) File "/var/lib/hudson/jobs/pip_python3.1/workspace/tests/tests_cache/test_ws/.virtualenv/lib/python3.1/site-packages/pip-1.0.1-py3.1.egg/pip/index.py", line 324, in _get_page return HTMLPage.get_page(link, req, cache=self.cache) File "/var/lib/hudson/jobs/pip_python3.1/workspace/tests/tests_cache/test_ws/.virtualenv/lib/python3.1/site-packages/pip-1.0.1-py3.1.egg/pip/index.py", line 445, in get_page inst = cls(u(resp.read()), real_url, headers) File "/var/lib/hudson/jobs/pip_python3.1/workspace/tests/tests_cache/test_ws/.virtualenv/lib/python3.1/site-packages/pip-1.0.1-py3.1.egg/pip/backwardcompat.py", line 58, in u return s.decode('utf-8') UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte ``` Running under pdb showed the page it was downloading was the pip homepage ie doing something like ``` python resp = urlopen('http://www.pip-installer.org/en/latest/') s = resp.read() s.decode('utf-8') ```
Note this patch wallpapers over the failure, but it'd be good to get to the root cause here https://gist.github.com/1004525 OK so saw some mention on the web a. that it might be gzipped, and 0x1f 0x8b is the start of a gzip encoded file I tried a tcpdump and that looked ok GET /en/latest/ HTTP/1.1 Host: www.pip-installer.org User-Agent: Python-urllib/3.2 Connection: close Accept-Encoding: identity HTTP/1.1 200 OK Server: nginx/0.8.54 Content-Type: text/html Last-Modified: Sun, 29 May 2011 12:11:33 GMT Content-Length: 29095 Date: Thu, 02 Jun 2011 15:35:46 GMT X-Varnish: 319516731 318923294 Age: 357612 Via: 1.1 varnish Connection: close GET /en/latest/index.html HTTP/1.1 Host: www.pip-installer.org User-Agent: Python-urllib/3.2 Connection: close Accept-Encoding: identity HTTP/1.1 200 OK Server: nginx/0.8.54 Content-Type: text/html Last-Modified: Sun, 29 May 2011 12:11:33 GMT Content-Encoding: gzip Content-Length: 9081 Date: Thu, 02 Jun 2011 15:46:04 GMT X-Varnish: 319517972 318923136 Age: 358332 Via: 1.1 varnish Connection: close ...........].r.........#."..l.mY..-..U|Q$9...)-H6I.@.....I..........q!)[..l.j...H.}..............N..$......7'G...v. Simple reproducer now: ``` python piptest.py Traceback (most recent call last): File "piptest.py", line 10, in <module> getpiphome() File "piptest.py", line 8, in getpiphome s = u(resp.read()) File "/Users/pnasrat/Development/pip/pip/backwardcompat.py", line 61, in u return s.decode('utf-8') UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte ``` ``` python #!/usr/bin/env python from pip.download import urlopen, geturl from pip.backwardcompat import u def getpiphome(): resp = urlopen('http://www.pip-installer.org/en/latest/index.html') url = geturl(resp) s = u(resp.read()) getpiphome() ``` Looks like bad caching on pip-installer.org can reproduce with netcat and ``` GET /en/latest/index.html HTTP/1.1 Host: www.pip-installer.org ```
2011-06-03T14:32:50Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python3.1/threading.py", line 516, in _bootstrap_inner self.run() File "/usr/local/lib/python3.1/threading.py", line 469, in run self._target(*self._args, **self._kwargs) File "/var/lib/hudson/jobs/pip_python3.1/workspace/tests/tests_cache/test_ws/.virtualenv/lib/python3.1/site-packages/pip-1.0.1-py3.1.egg/pip/index.py", line 239, in _get_queued_page page = self._get_page(location, req) File "/var/lib/hudson/jobs/pip_python3.1/workspace/tests/tests_cache/test_ws/.virtualenv/lib/python3.1/site-packages/pip-1.0.1-py3.1.egg/pip/index.py", line 324, in _get_page return HTMLPage.get_page(link, req, cache=self.cache) File "/var/lib/hudson/jobs/pip_python3.1/workspace/tests/tests_cache/test_ws/.virtualenv/lib/python3.1/site-packages/pip-1.0.1-py3.1.egg/pip/index.py", line 445, in get_page inst = cls(u(resp.read()), real_url, headers) File "/var/lib/hudson/jobs/pip_python3.1/workspace/tests/tests_cache/test_ws/.virtualenv/lib/python3.1/site-packages/pip-1.0.1-py3.1.egg/pip/backwardcompat.py", line 58, in u return s.decode('utf-8') UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte
17,241
pypa/pip
pypa__pip-3088
bd863d7c6efd8cc8a0b41934766c8db561e57bc9
diff --git a/pip/wheel.py b/pip/wheel.py --- a/pip/wheel.py +++ b/pip/wheel.py @@ -25,7 +25,8 @@ import pip from pip.download import path_to_url, unpack_url -from pip.exceptions import InvalidWheelFilename, UnsupportedWheel +from pip.exceptions import ( + InstallationError, InvalidWheelFilename, UnsupportedWheel) from pip.locations import distutils_scheme, PIP_DELETE_MARKER_FILENAME from pip import pep425tags from pip.utils import ( @@ -390,6 +391,13 @@ def is_entrypoint_wrapper(name): # See https://bitbucket.org/pypa/distlib/issue/34/ # See https://bitbucket.org/pypa/distlib/issue/33/ def _get_script_text(entry): + if entry.suffix is None: + raise InstallationError( + "Invalid script entry point: %s for req: %s - A callable " + "suffix is required. Cf https://packaging.python.org/en/" + "latest/distributing.html#console-scripts for more " + "information." % (entry, req) + ) return maker.script_template % { "module": entry.prefix, "import_name": entry.suffix.split(".")[0],
AttributeError: 'NoneType' object has no attribute 'split' `pip install -r <whatever>` leads to the following error for SOME requirements sets. I cannot tell you which package is the cause, because the installation is rather huge and pip prevents me from debugging by just echoing the error instead of populating the exception to the main method (so no ipython/ipdb). ``` Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip/commands/install.py", line 299, in run root=options.root_path, File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 646, in install **kwargs File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 813, in install self.move_wheel_files(self.source_dir, root=root) File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 1008, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 479, in move_wheel_files maker.make_multiple(['%s = %s' % kv for kv in console.items()]) File "/usr/local/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", line 334, in make_multiple filenames.extend(self.make(specification, options)) File "/usr/local/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", line 323, in make self._make_script(entry, filenames, options=options) File "/usr/local/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", line 214, in _make_script script = self._get_script_text(entry).encode('utf-8') File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 396, in _get_script_text "import_name": entry.suffix.split(".")[0], AttributeError: 'NoneType' object has no attribute 'split' ```
Unfortunately, this is not very useful. All we can say is that one of the dependencies has an unusual `console_scripts` entry point declaration. Could you maybe split your requirement files several times to identify the culprit distribution via dichotomy ? OK, I'll try that, but it takes some time... Thanks for the `console_scripts` hint. @xavfernandez The error happens in the following situation: you have a `setup.py` with the following construction: ``` setup( ... entry_points={ 'console_scripts': [ 'mycommand = mypkg.sub.a.b:main' ], ... }, ... ) ``` And the package (`mypkg.sub.a.b`) does not exist. However, the issue is still valid because: 1. The error is misleading and does not help at all. 2. It does not occur on a regular base in case you have an old `setup.pyc` file around (which turned to be the cause in my case). That one is not the fault of pip, but it makes tracking down the issue even harder. I propose to add an if-check or try-except block at the right place and inform the user that there is something wrong with the `console_script`. Thanks for taking the time to investigate. But I don't think that's the root cause. In your case, you seem to have an `entry.suffix` equal to `None`, which would point to an entry point like: `'mycommand = mypkg.sub.a.b:'` or `'mycommand = mypkg.sub.a.b'` (i.e. without `:something` suffix) Anyhow, the error message could certainly be improved. A simple raise in https://github.com/pypa/pip/blob/develop/pip/wheel.py#L393-L398 if `entry.suffix is None` could do the trick.
2015-09-09T21:09:36Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip/commands/install.py", line 299, in run root=options.root_path, File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 646, in install **kwargs File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 813, in install self.move_wheel_files(self.source_dir, root=root) File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 1008, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 479, in move_wheel_files maker.make_multiple(['%s = %s' % kv for kv in console.items()]) File "/usr/local/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", line 334, in make_multiple filenames.extend(self.make(specification, options)) File "/usr/local/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", line 323, in make self._make_script(entry, filenames, options=options) File "/usr/local/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", line 214, in _make_script script = self._get_script_text(entry).encode('utf-8') File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 396, in _get_script_text "import_name": entry.suffix.split(".")[0], AttributeError: 'NoneType' object has no attribute 'split'
17,252
pypa/pip
pypa__pip-3136
f8377a4ee67a927ba49d7d5da2ed43088de86f77
diff --git a/pip/compat/__init__.py b/pip/compat/__init__.py --- a/pip/compat/__init__.py +++ b/pip/compat/__init__.py @@ -101,6 +101,18 @@ def get_path_uid(path): return file_uid +def expanduser(path): + """ + Expand ~ and ~user constructions. + + Includes a workaround for http://bugs.python.org/issue14768 + """ + expanded = os.path.expanduser(path) + if path.startswith('~/') and expanded.startswith('//'): + expanded = expanded[1:] + return expanded + + # packages in the stdlib that may have installation metadata, but should not be # considered 'installed'. this theoretically could be determined based on # dist.location (py27:`sysconfig.get_paths()['stdlib']`, diff --git a/pip/locations.py b/pip/locations.py --- a/pip/locations.py +++ b/pip/locations.py @@ -9,7 +9,7 @@ from distutils import sysconfig from distutils.command.install import install, SCHEME_KEYS # noqa -from pip.compat import WINDOWS +from pip.compat import WINDOWS, expanduser from pip.utils import appdirs @@ -114,7 +114,7 @@ def virtualenv_no_global(): site_packages = sysconfig.get_python_lib() user_site = site.USER_SITE -user_dir = os.path.expanduser('~') +user_dir = expanduser('~') if WINDOWS: bin_py = os.path.join(sys.prefix, 'Scripts') bin_user = os.path.join(user_site, 'Scripts') diff --git a/pip/req/req_set.py b/pip/req/req_set.py --- a/pip/req/req_set.py +++ b/pip/req/req_set.py @@ -9,6 +9,7 @@ from pip._vendor import pkg_resources from pip._vendor import requests +from pip.compat import expanduser from pip.download import (url_to_path, unpack_url) from pip.exceptions import (InstallationError, BestVersionAlreadyInstalled, DistributionNotFound, PreviousBuildDirError) @@ -290,7 +291,7 @@ def has_requirements(self): @property def is_download(self): if self.download_dir: - self.download_dir = os.path.expanduser(self.download_dir) + self.download_dir = expanduser(self.download_dir) if os.path.exists(self.download_dir): return True else: diff --git a/pip/utils/__init__.py b/pip/utils/__init__.py --- a/pip/utils/__init__.py +++ b/pip/utils/__init__.py @@ -15,7 +15,7 @@ import zipfile from pip.exceptions import InstallationError -from pip.compat import console_to_str, stdlib_pkgs +from pip.compat import console_to_str, expanduser, stdlib_pkgs from pip.locations import ( site_packages, user_site, running_under_virtualenv, virtualenv_no_global, write_delete_marker_file, @@ -252,7 +252,7 @@ def normalize_path(path, resolve_symlinks=True): Convert a path to its canonical, case-normalized, absolute version. """ - path = os.path.expanduser(path) + path = expanduser(path) if resolve_symlinks: path = os.path.realpath(path) else: diff --git a/pip/utils/appdirs.py b/pip/utils/appdirs.py --- a/pip/utils/appdirs.py +++ b/pip/utils/appdirs.py @@ -7,7 +7,7 @@ import os import sys -from pip.compat import WINDOWS +from pip.compat import WINDOWS, expanduser def user_cache_dir(appname): @@ -39,13 +39,13 @@ def user_cache_dir(appname): path = os.path.join(path, appname, "Cache") elif sys.platform == "darwin": # Get the base path - path = os.path.expanduser("~/Library/Caches") + path = expanduser("~/Library/Caches") # Add our app name to it path = os.path.join(path, appname) else: # Get the base path - path = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")) + path = os.getenv("XDG_CACHE_HOME", expanduser("~/.cache")) # Add our app name to it path = os.path.join(path, appname) @@ -85,12 +85,12 @@ def user_data_dir(appname, roaming=False): path = os.path.join(os.path.normpath(_get_win_folder(const)), appname) elif sys.platform == "darwin": path = os.path.join( - os.path.expanduser('~/Library/Application Support/'), + expanduser('~/Library/Application Support/'), appname, ) else: path = os.path.join( - os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share")), + os.getenv('XDG_DATA_HOME', expanduser("~/.local/share")), appname, ) @@ -122,7 +122,7 @@ def user_config_dir(appname, roaming=True): elif sys.platform == "darwin": path = user_data_dir(appname) else: - path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config")) + path = os.getenv('XDG_CONFIG_HOME', expanduser("~/.config")) path = os.path.join(path, appname) return path @@ -156,7 +156,7 @@ def site_config_dirs(appname): xdg_config_dirs = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg') if xdg_config_dirs: pathlist = [ - os.sep.join([os.path.expanduser(x), appname]) + os.sep.join([expanduser(x), appname]) for x in xdg_config_dirs.split(os.pathsep) ] else: diff --git a/pip/wheel.py b/pip/wheel.py --- a/pip/wheel.py +++ b/pip/wheel.py @@ -24,6 +24,7 @@ from pip._vendor.six import StringIO import pip +from pip.compat import expanduser from pip.download import path_to_url, unpack_url from pip.exceptions import ( InstallationError, InvalidWheelFilename, UnsupportedWheel) @@ -55,7 +56,7 @@ def __init__(self, cache_dir, format_control): :param format_control: A pip.index.FormatControl object to limit binaries being read from the cache. """ - self._cache_dir = os.path.expanduser(cache_dir) if cache_dir else None + self._cache_dir = expanduser(cache_dir) if cache_dir else None self._format_control = format_control def cached_wheel(self, link, package_name):
Error when installing buildbot-slave in pip 7.0.0 and later I get an error when installing buildbot-slave using pip 7.0.0 - 7.1.0: ``` # pip install buildbot-slave Collecting buildbot-slave /usr/local/lib/python2.6/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Downloading buildbot-slave-0.8.12.tar.gz (118kB) 100% |################################| 118kB 3.3MB/s Collecting twisted>=8.0.0 (from buildbot-slave) Downloading Twisted-15.2.1.tar.bz2 (4.6MB) 100% |################################| 4.6MB 160kB/s Collecting zope.interface>=3.6.0 (from twisted>=8.0.0->buildbot-slave) Downloading zope.interface-4.1.2.tar.gz (919kB) 100% |################################| 921kB 792kB/s Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/local/lib/python2.6/dist-packages (from zope.interface>=3.6.0->twisted>=8.0.0->buildbot-slave) Building wheels for collected packages: buildbot-slave, twisted, zope.interface Running setup.py bdist_wheel for buildbot-slave Stored in directory: //.cache/pip/wheels/34/64/c3/3efbca6046b0bbe09f8386890bf3865f3caba5ba7534e7af1f Exception: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/usr/local/lib/python2.6/dist-packages/pip/commands/install.py", line 293, in run wb.build(autobuilding=True) File "/usr/local/lib/python2.6/dist-packages/pip/wheel.py", line 787, in build build_failure.append(req) File "/usr/lib/python2.6/contextlib.py", line 34, in __exit__ self.gen.throw(type, value, traceback) File "/usr/local/lib/python2.6/dist-packages/pip/utils/logging.py", line 36, in indent_log yield File "/usr/local/lib/python2.6/dist-packages/pip/wheel.py", line 785, in build session=self.requirement_set.session) File "/usr/local/lib/python2.6/dist-packages/pip/download.py", line 814, in unpack_url unpack_file_url(link, location, download_dir) File "/usr/local/lib/python2.6/dist-packages/pip/download.py", line 723, in unpack_file_url unpack_file(from_path, location, content_type, link) File "/usr/local/lib/python2.6/dist-packages/pip/utils/__init__.py", line 644, in unpack_file flatten=not filename.endswith('.whl') File "/usr/local/lib/python2.6/dist-packages/pip/utils/__init__.py", line 528, in unzip_file zipfp = open(filename, 'rb') IOError: [Errno 2] No such file or directory: '/\\\\.cache/pip/wheels/34/64/c3/3efbca6046b0bbe09f8386890bf3865f3caba5ba7534e7af1f/buildbot_slave-0.8.12-py2-none-any.whl' ``` The same package installs correctly with pip version 6.1.1.
Does not look like it's related to `buildbot-slave`: pip seems to build a wheel successfully for it in `//.cache/pip/wheels/34/64/c3/3efbca6046b0bbe09f8386890bf3865f3caba5ba7534e7af1f` but does not find it a few lines after... Could you retry the install and check what is in the directory reported here: ``` Building wheels for collected packages: buildbot-slave, twisted, zope.interface Running setup.py bdist_wheel for buildbot-slave Stored in directory: *THIS DIRECTORY* ``` Did you try running `pip install twisted` alone for example to check if it is `buildbot-slave` specific ? And what is you OS ? And the content of the environment variable $HOME ? (you seem to be running as root) For the record, pip 7.1.0 seems to install correctly `buildbot-slave` on my end. The directory `//.cache/pip/wheels/34/64/c3/3efbca6046b0bbe09f8386890bf3865f3caba5ba7534e7af1f` specified in "Stored in this directory" contains a single file `buildbot_slave-0.8.12-py2-none-any.whl`. Similar error occurs when I try to install `twisted`: ``` IOError: [Errno 2] No such file or directory: '/home/\\\\.cache/pip/wheels/a0/10/c4/3b2e14dad063e87d188eb2503861413db1fea43ded77834299/zope.interface-4.1.2-cp26-none-linux_x86_64.whl' ``` Note that in both cases the problem is that the paths contain extra `\\\\`. The error occurs on a Docker box running Ubuntu 10.04 and `$HOME` is set to `/` (not sure why, but it's a throwaway box, so I didn't care to change anything). Ok, for the record, that's what I'm getting: ``` >>> import os >>> os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")) '//.cache' ``` Which is certainly transformed in pip into: ``` In [1]: from pip.download import path_to_url, url_to_path In [2]: path_to_url('//.cache/path_to_some_wheel.whl') Out[2]: 'file://.cache/path_to_some_wheel.whl' ``` Which unfortunately transformed back to: ``` In [3]: url_to_path('file://.cache/path_to_some_wheel.whl') Out[3]: '\\\\.cache/path_to_some_wheel.whl' ``` In the meantime, running `HOME=/root pip install buildbot-slave`, seems to work. Thanks for the workaround, setting `HOME` to something other than `/` does solve the problem. It would be nice if it worked with `HOME=/` too because this seems to be the default on many Docker images.
2015-09-24T03:13:44Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/pip/basecommand.py", line 223, in main status = self.run(options, args) File "/usr/local/lib/python2.6/dist-packages/pip/commands/install.py", line 293, in run wb.build(autobuilding=True) File "/usr/local/lib/python2.6/dist-packages/pip/wheel.py", line 787, in build build_failure.append(req) File "/usr/lib/python2.6/contextlib.py", line 34, in __exit__ self.gen.throw(type, value, traceback) File "/usr/local/lib/python2.6/dist-packages/pip/utils/logging.py", line 36, in indent_log yield File "/usr/local/lib/python2.6/dist-packages/pip/wheel.py", line 785, in build session=self.requirement_set.session) File "/usr/local/lib/python2.6/dist-packages/pip/download.py", line 814, in unpack_url unpack_file_url(link, location, download_dir) File "/usr/local/lib/python2.6/dist-packages/pip/download.py", line 723, in unpack_file_url unpack_file(from_path, location, content_type, link) File "/usr/local/lib/python2.6/dist-packages/pip/utils/__init__.py", line 644, in unpack_file flatten=not filename.endswith('.whl') File "/usr/local/lib/python2.6/dist-packages/pip/utils/__init__.py", line 528, in unzip_file zipfp = open(filename, 'rb') IOError: [Errno 2] No such file or directory: '/\\\\.cache/pip/wheels/34/64/c3/3efbca6046b0bbe09f8386890bf3865f3caba5ba7534e7af1f/buildbot_slave-0.8.12-py2-none-any.whl'
17,255
pypa/pip
pypa__pip-3203
2f14ae55e2e356f28a3dd7c4703be408eeb681d7
diff --git a/pip/req/req_install.py b/pip/req/req_install.py --- a/pip/req/req_install.py +++ b/pip/req/req_install.py @@ -15,6 +15,7 @@ from pip._vendor import pkg_resources, six from pip._vendor.distlib.markers import interpret as markers_interpret +from pip._vendor.packaging import specifiers from pip._vendor.six.moves import configparser import pip.wheel @@ -44,6 +45,8 @@ logger = logging.getLogger(__name__) +operators = specifiers.Specifier._operators.keys() + def _strip_extras(path): m = re.match(r'^(.+)(\[[^\]]+\])$', path) @@ -65,7 +68,17 @@ def __init__(self, req, comes_from, source_dir=None, editable=False, wheel_cache=None, constraint=False): self.extras = () if isinstance(req, six.string_types): - req = pkg_resources.Requirement.parse(req) + try: + req = pkg_resources.Requirement.parse(req) + except pkg_resources.RequirementParseError: + if os.path.sep in req: + add_msg = "It looks like a path. Does it exist ?" + elif '=' in req and not any(op in req for op in operators): + add_msg = "= is not a valid operator. Did you mean == ?" + else: + add_msg = traceback.format_exc() + raise InstallationError( + "Invalid requirement: '%s'\n%s" % (req, add_msg)) self.extras = req.extras self.req = req
Traceback on invalid version spec Invalid version specification should not give a trace back. ``` $ pip install pyprocessing=0.1.3.21 Exception: Traceback (most recent call last): File "/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main status = self.run(options, args) File "/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 214, in run InstallRequirement.from_line(name, None)) File "/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 107, in from_line return cls(req, comes_from, url=url) File "/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 40, in __init__ req = pkg_resources.Requirement.parse(req) File "/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2510, in parse reqs = list(parse_requirements(s)) File "/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2436, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2404, in scan_list raise ValueError("Expected "+item_name+" in",line,"at",line[p:]) ValueError: ('Expected version spec in', 'pyprocessing=0.1.3.21', 'at', '=0.1.3.21') ```
Confirmed on develop Will try get to tomorrow. If you are at it, pyprocessing=0.3.11 could be a valid version spec. It's not a python code anyway - why constrain users? The specification is defined by setuptools/easyinstall not pip and is `==` see http://packages.python.org/distribute/setuptools.html#declaring-dependencies
2015-10-23T21:02:10Z
[]
[]
Traceback (most recent call last): File "/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/basecommand.py", line 104, in main status = self.run(options, args) File "/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/commands/install.py", line 214, in run InstallRequirement.from_line(name, None)) File "/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 107, in from_line return cls(req, comes_from, url=url) File "/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 40, in __init__ req = pkg_resources.Requirement.parse(req) File "/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2510, in parse reqs = list(parse_requirements(s)) File "/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2436, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2404, in scan_list raise ValueError("Expected "+item_name+" in",line,"at",line[p:]) ValueError: ('Expected version spec in', 'pyprocessing=0.1.3.21', 'at', '=0.1.3.21')
17,259
pypa/pip
pypa__pip-3346
637ffc1b0146c02b1fc20824ac62872fe3b12310
diff --git a/pip/vcs/subversion.py b/pip/vcs/subversion.py --- a/pip/vcs/subversion.py +++ b/pip/vcs/subversion.py @@ -163,8 +163,13 @@ def get_url(self, location): def _get_svn_url_rev(self, location): from pip.exceptions import InstallationError - with open(os.path.join(location, self.dirname, 'entries')) as f: - data = f.read() + entries_path = os.path.join(location, self.dirname, 'entries') + if os.path.exists(entries_path): + with open(entries_path) as f: + data = f.read() + else: # subversion >= 1.7 does not have the 'entries' file + data = '' + if (data.startswith('8') or data.startswith('9') or data.startswith('10')):
'freeze' and SVN 1.7/1.8 exception and fix I'm running pip 1.3.1 and despite the #369 fix it is still unable to run 'pip freeze' with SVN 1.7 or 1.8. My SVN check-outs do not contain a ".svn/entries" file and it fails on this before getting to the fix from #369. I have a quick fix (of sorts), below. First, the exception: ``` # pip freeze Exception: Traceback (most recent call last): File "pip/basecommand.py", line 139, in main status = self.run(options, args) File "pip/commands/freeze.py", line 73, in run req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags) File "pip/__init__.py", line 181, in from_dist req = get_src_requirement(dist, location, find_tags) File "pip/vcs/__init__.py", line 249, in get_src_requirement return version_control().get_src_requirement(dist, location, find_tags) File "pip/vcs/subversion.py", line 213, in get_src_requirement repo = self.get_url(location) File "pip/vcs/subversion.py", line 156, in get_url return self._get_svn_url_rev(location)[0] File "pip/vcs/subversion.py", line 159, in _get_svn_url_rev f = open(os.path.join(location, self.dirname, 'entries')) IOError: [Errno 2] No such file or directory: 'xmlbuilder/.svn/entries' Storing complete log in /root/.pip/pip.log ``` The contents of .svn (SVN itself appears to be working fine). ``` # ls xmlbuilder/.svn/ pristine tmp wc.db ``` My SVN checkouts are all 'svn upgrade'd from SVN 1.6 to 1.7 to 1.8. Excuse the quick hack, but this is enough to get it working: ``` # diff pip/vcs/subversion.py.back pip/vcs/subversion.py 159,161c159,164 < f = open(os.path.join(location, self.dirname, 'entries')) < data = f.read() < f.close() --- > try: > f = open(os.path.join(location, self.dirname, 'entries')) > data = f.read() > f.close() > except: > data = "SVN >=1.7" ``` This allows the IOError to pass, and the #369 fix kicks into action because the contents of 'data' can't be parsed as SVN <= 1.6.
2016-01-07T22:27:15Z
[]
[]
Traceback (most recent call last): File "pip/basecommand.py", line 139, in main status = self.run(options, args) File "pip/commands/freeze.py", line 73, in run req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags) File "pip/__init__.py", line 181, in from_dist req = get_src_requirement(dist, location, find_tags) File "pip/vcs/__init__.py", line 249, in get_src_requirement return version_control().get_src_requirement(dist, location, find_tags) File "pip/vcs/subversion.py", line 213, in get_src_requirement repo = self.get_url(location) File "pip/vcs/subversion.py", line 156, in get_url return self._get_svn_url_rev(location)[0] File "pip/vcs/subversion.py", line 159, in _get_svn_url_rev f = open(os.path.join(location, self.dirname, 'entries')) IOError: [Errno 2] No such file or directory: 'xmlbuilder/.svn/entries'
17,272
pypa/pip
pypa__pip-3397
4beeee636c1484d8d7869b73e6ad098bd6581e25
diff --git a/pip/pep425tags.py b/pip/pep425tags.py --- a/pip/pep425tags.py +++ b/pip/pep425tags.py @@ -116,8 +116,8 @@ def get_platform(): # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may # be signficantly older than the user's current machine. release, _, machine = platform.mac_ver() - major, minor, micro = release.split('.') - return 'macosx_{0}_{1}_{2}'.format(major, minor, machine) + split_ver = release.split('.') + return 'macosx_{0}_{1}_{2}'.format(split_ver[0], split_ver[1], machine) # XXX remove distutils dependency return distutils.util.get_platform().replace('.', '_').replace('-', '_')
ValueError while unpacking platform.mac_ver() on OS X 10.11 on Travis `osx10.11` image, I am getting `ValueError` while trying to run `python get-pip.py --user` with El Capitan's built-in python 2.7.10: ``` Traceback (most recent call last): File "get-pip.py", line 19000, in <module> main() File "get-pip.py", line 179, in main bootstrap(tmpdir=tmpdir) File "get-pip.py", line 82, in bootstrap import pip File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/__init__.py", line 15, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/vcs/subversion.py", line 9, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/index.py", line 29, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/wheel.py", line 32, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/pep425tags.py", line 214, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/pep425tags.py", line 162, in get_supported File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/pep425tags.py", line 119, in get_platform ValueError: need more than 2 values to unpack ``` Full log here: https://travis-ci.org/behdad/fonttools/jobs/103554883 I think it's because of this commit: https://github.com/pypa/pip/commit/995deff93977fbb85d07df3e4c15388f0f0140e2 It looks like `platform.mac_ver()` doesn't always return a tuple of 3 elements, but sometimes only 2...
Yep. ``` python python -c 'import platform; print platform.mac_ver()' ('10.11', ('', '', ''), 'x86_64') ``` https://travis-ci.org/anthrotype/fonttools/jobs/103565174#L1444 /cc @rmcgibbo I encountered the issue during an uninstall command. If anybody needs a quick fix, open `site-packages/pip/pep425tags.py`, head to line 118, and change `get_platform()` to something like: ``` python def get_platform(): """Return our platform name 'win32', 'linux_x86_64'""" if sys.platform == 'darwin': # distutils.util.get_platform() returns the release based on the value # of MACOSX_DEPLOYMENT_TARGET on which Python was built, which may # be signficantly older than the user's current machine. release, _, machine = platform.mac_ver() split_ver = release.split('.') return 'macosx_{0}_{1}_{2}'.format(split_ver[0], split_ver[1], machine) # XXX remove distutils dependency return distutils.util.get_platform().replace('.', '_').replace('-', '_') ``` Worked for me!
2016-01-20T14:07:11Z
[]
[]
Traceback (most recent call last): File "get-pip.py", line 19000, in <module> main() File "get-pip.py", line 179, in main bootstrap(tmpdir=tmpdir) File "get-pip.py", line 82, in bootstrap import pip File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/__init__.py", line 15, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/vcs/subversion.py", line 9, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/index.py", line 29, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/wheel.py", line 32, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/pep425tags.py", line 214, in <module> File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/pep425tags.py", line 162, in get_supported File "/var/folders/my/m6ynh3bn6tq06h7xr3js0z7r0000gn/T/tmpZ_zMd5/pip.zip/pip/pep425tags.py", line 119, in get_platform ValueError: need more than 2 values to unpack
17,278
pypa/pip
pypa__pip-3485
0c73957b6d3b4b49bc08c04568e1f1090b38c022
diff --git a/pip/download.py b/pip/download.py --- a/pip/download.py +++ b/pip/download.py @@ -29,6 +29,7 @@ from pip.utils import (splitext, rmtree, format_size, display_path, backup_dir, ask_path_exists, unpack_file, ARCHIVE_EXTENSIONS, consume, call_subprocess) +from pip.utils.encoding import auto_decode from pip.utils.filesystem import check_path_owner from pip.utils.logging import indent_log from pip.utils.setuptools_build import SETUPTOOLS_SHIM @@ -407,14 +408,10 @@ def get_file_content(url, comes_from=None, session=None): # FIXME: catch some errors resp = session.get(url) resp.raise_for_status() - - if six.PY3: - return resp.url, resp.text - else: - return resp.url, resp.content + return resp.url, resp.text try: - with open(url) as f: - content = f.read() + with open(url, 'rb') as f: + content = auto_decode(f.read()) except IOError as exc: raise InstallationError( 'Could not open requirements file: %s' % str(exc) diff --git a/pip/req/req_file.py b/pip/req/req_file.py --- a/pip/req/req_file.py +++ b/pip/req/req_file.py @@ -7,6 +7,7 @@ import os import re import shlex +import sys import optparse import warnings @@ -133,6 +134,9 @@ def process_line(line, filename, line_number, finder=None, comes_from=None, # `finder.format_control` will be updated during parsing defaults.format_control = finder.format_control args_str, options_str = break_args_options(line) + if sys.version_info < (2, 7, 3): + # Priori to 2.7.3, shlex can not deal with unicode entries + options_str = options_str.encode('utf8') opts, _ = parser.parse_args(shlex.split(options_str), defaults) # preserve for the nested code path diff --git a/pip/utils/encoding.py b/pip/utils/encoding.py new file mode 100644 --- /dev/null +++ b/pip/utils/encoding.py @@ -0,0 +1,23 @@ +import codecs +import locale + + +BOMS = [ + (codecs.BOM_UTF8, 'utf8'), + (codecs.BOM_UTF16, 'utf16'), + (codecs.BOM_UTF16_BE, 'utf16-be'), + (codecs.BOM_UTF16_LE, 'utf16-le'), + (codecs.BOM_UTF32, 'utf32'), + (codecs.BOM_UTF32_BE, 'utf32-be'), + (codecs.BOM_UTF32_LE, 'utf32-le'), +] + + +def auto_decode(data): + """Check a bytes string for a BOM to correctly detect the encoding + + Fallback to locale.getpreferredencoding(False) like open() on Python3""" + for bom, encoding in BOMS: + if data.startswith(bom): + return data[len(bom):].decode(encoding) + return data.decode(locale.getpreferredencoding(False))
Error running pip install -r <requirements file> Python 3.4 / Windows 7 / Powershell / pip version 7.0.3 Running ``` pip install -r .\stable-req.txt ``` with stable-req.txt containing requests==2.7.0 results in the following exception: ``` Traceback (most recent call last): File "D:\frh\env2\lib\site-packages\pip\basecommand.py", line 223, in main status = self.run(options, args) File "D:\frh\env2\lib\site-packages\pip\commands\install.py", line 268, in run wheel_cache File "D:\frh\env2\lib\site-packages\pip\basecommand.py", line 287, in populate_requirement_set wheel_cache=wheel_cache): File "D:\frh\env2\lib\site-packages\pip\req\req_file.py", line 86, in parse_requirements for req in req_iter: File "D:\frh\env2\lib\site-packages\pip\req\req_file.py", line 130, in process_line wheel_cache=wheel_cache File "D:\frh\env2\lib\site-packages\pip\req\req_install.py", line 207, in from_line wheel_cache=wheel_cache) File "D:\frh\env2\lib\site-packages\pip\req\req_install.py", line 66, in __init__ req = pkg_resources.Requirement.parse(req) File "D:\frh\env2\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2960, in parse reqs = list(parse_requirements(s)) File "D:\frh\env2\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2904, in parse_requirements "version spec") File "D:\frh\env2\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2869, in scan_list raise ValueError(msg, line, "at", line[p:]) ValueError: ('Expected version spec in', 'ÿþr\x00e\x00q\x00u\x00e\x00s\x00t\x00s\x00=\x00=\x002\x00.\x007\x00.\x000\x00' , 'at', '\x00e\x00q\x00u\x00e\x00s\x00t\x00s\x00=\x00=\x002\x00.\x007\x00.\x000\x00') ``` Reproduced on two pcs and one Windows Server 2008 r2
looks like a big pile of encoding confusion. Is that UCS32 perhaps? ``` >>> u"ÿþr\x00e\x00q\x00u\x00e\x00s\x00t\x00s\x00=\x00=\x002\x00.\x007\x00.\x000\x00".encode('utf8') b'\xc3\xbf\xc3\xber\x00e\x00q\x00u\x00e\x00s\x00t\x00s\x00=\x00=\x002\x00.\x007\x00.\x000\x00' >>> u"ÿþr\x00e\x00q\x00u\x00e\x00s\x00t\x00s\x00=\x00=\x002\x00.\x007\x00.\x000\x00".encode('utf8').decode('utf16') '뿃뻃requests==2.7.0' ``` and `ÿþ` seems to corresponds to the UTF-16 (LE) BOM (cf https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding), which would match. So I'd guess the req file was encoded in utf16 but python opened it as utf8 (returned from `locale.getpreferredencoding()` if I understand correctly https://docs.python.org/3.4/library/functions.html#open). Not sure what pip could do to improve the user experience on such case ... Yeah, that's a UTF-16 file. Was it created by redirection in Powershell (`some_cmd > stable-req.txt`) ? As that is typically where I end up with UTF-16 files that I didn't want ;-) Auto-detecting (guessing) encodings is generally a bad idea, and probably something pip shouldn't get into, but I guess that looking for a BOM when reading the requirements file, and choosing the encoding from that if it's found, would be a useful feature to help with this common Windows issue. (Although it's mainly a Windows issue, the BOM detection can be added for all platforms, as I can't see how it would cause a problem on any other platform). Duplicate of #733
2016-02-12T22:43:47Z
[]
[]
Traceback (most recent call last): File "D:\frh\env2\lib\site-packages\pip\basecommand.py", line 223, in main status = self.run(options, args) File "D:\frh\env2\lib\site-packages\pip\commands\install.py", line 268, in run wheel_cache File "D:\frh\env2\lib\site-packages\pip\basecommand.py", line 287, in populate_requirement_set wheel_cache=wheel_cache): File "D:\frh\env2\lib\site-packages\pip\req\req_file.py", line 86, in parse_requirements for req in req_iter: File "D:\frh\env2\lib\site-packages\pip\req\req_file.py", line 130, in process_line wheel_cache=wheel_cache File "D:\frh\env2\lib\site-packages\pip\req\req_install.py", line 207, in from_line wheel_cache=wheel_cache) File "D:\frh\env2\lib\site-packages\pip\req\req_install.py", line 66, in __init__ req = pkg_resources.Requirement.parse(req) File "D:\frh\env2\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2960, in parse reqs = list(parse_requirements(s)) File "D:\frh\env2\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2904, in parse_requirements "version spec") File "D:\frh\env2\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 2869, in scan_list raise ValueError(msg, line, "at", line[p:]) ValueError: ('Expected version spec in', 'ÿþr\x00e\x00q\x00u\x00e\x00s\x00t\x00s\x00=\x00=\x002\x00.\x007\x00.\x000\x00'
17,286
pypa/pip
pypa__pip-3522
f5d27846c2c47b8bf0bdf3c14b53fad429e5a1d4
diff --git a/pip/utils/__init__.py b/pip/utils/__init__.py --- a/pip/utils/__init__.py +++ b/pip/utils/__init__.py @@ -703,7 +703,8 @@ def call_subprocess(cmd, show_stdout=True, cwd=None, spinner.finish("done") if proc.returncode: if on_returncode == 'raise': - if logger.getEffectiveLevel() > std_logging.DEBUG: + if (logger.getEffectiveLevel() > std_logging.DEBUG and + not show_stdout): logger.info( 'Complete output from command %s:', command_desc, )
Error when call_subprocess fails with show_stdout=True If `call_subprocess` in `utils/__init__.py` is called with `show_stdout=True`, and the subprocess fails, pip errors out with `UnboundLocalError: local variable 'all_output' referenced before assignment`. To avoid this, it should not try to print `all_output` when called when `show_stdout=True`. In this case, the process's stdout will already be printed to the console. Discovered using this command: ``` $ pip install git+ssh://git@github.com:uber/vertica-python.git@0.2.1 Collecting git+ssh://git@github.com:uber/vertica-python.git@0.2.1 Cloning ssh://git@github.com:uber/vertica-python.git (to 0.2.1) to /tmp/pip-8k63_T-build ssh: Could not resolve hostname github.com:uber: Name or service not known fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. git clone -q ssh://git@github.com:uber/vertica-python.git /tmp/pip-8k63_T-build Complete output from command git clone -q ssh://git@github.com:uber/vertica-python.git /tmp/pip-8k63_T-build: Exception: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 299, in run requirement_set.prepare_files(finder) File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 359, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 576, in _prepare_file session=self.session, hashes=hashes) File "/usr/lib/python2.7/site-packages/pip/download.py", line 793, in unpack_url unpack_vcs_link(link, location) File "/usr/lib/python2.7/site-packages/pip/download.py", line 474, in unpack_vcs_link vcs_backend.unpack(location) File "/usr/lib/python2.7/site-packages/pip/vcs/__init__.py", line 283, in unpack self.obtain(location) File "/usr/lib/python2.7/site-packages/pip/vcs/git.py", line 124, in obtain self.run_command(['clone', '-q', url, dest]) File "/usr/lib/python2.7/site-packages/pip/vcs/__init__.py", line 322, in run_command spinner) File "/usr/lib/python2.7/site-packages/pip/utils/__init__.py", line 712, in call_subprocess ''.join(all_output) + UnboundLocalError: local variable 'all_output' referenced before assignment ```
2016-02-26T21:30:43Z
[]
[]
Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 299, in run requirement_set.prepare_files(finder) File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 359, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python2.7/site-packages/pip/req/req_set.py", line 576, in _prepare_file session=self.session, hashes=hashes) File "/usr/lib/python2.7/site-packages/pip/download.py", line 793, in unpack_url unpack_vcs_link(link, location) File "/usr/lib/python2.7/site-packages/pip/download.py", line 474, in unpack_vcs_link vcs_backend.unpack(location) File "/usr/lib/python2.7/site-packages/pip/vcs/__init__.py", line 283, in unpack self.obtain(location) File "/usr/lib/python2.7/site-packages/pip/vcs/git.py", line 124, in obtain self.run_command(['clone', '-q', url, dest]) File "/usr/lib/python2.7/site-packages/pip/vcs/__init__.py", line 322, in run_command spinner) File "/usr/lib/python2.7/site-packages/pip/utils/__init__.py", line 712, in call_subprocess ''.join(all_output) + UnboundLocalError: local variable 'all_output' referenced before assignment
17,289
pypa/pip
pypa__pip-3539
3646201f0efc4d41085c12dcf81a1fd1a7d8a2a4
diff --git a/pip/req/req_install.py b/pip/req/req_install.py --- a/pip/req/req_install.py +++ b/pip/req/req_install.py @@ -1090,9 +1090,9 @@ def _build_req_from_url(url): parts = [p for p in url.split('#', 1)[0].split('/') if p] req = None - if parts[-2] in ('tags', 'branches', 'tag', 'branch'): + if len(parts) > 2 and parts[-2] in ('tags', 'branches', 'tag', 'branch'): req = parts[-3] - elif parts[-1] == 'trunk': + elif len(parts) > 1 and parts[-1] == 'trunk': req = parts[-2] if req: warnings.warn(
Invalid package name argument to `pip install` can output an IndexError `pip install -e git+` will yield: ``` Traceback (most recent call last): File "/PATH/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/PATH/site-packages/pip/commands/install.py", line 287, in run wheel_cache File "/PATH/site-packages/pip/basecommand.py", line 280, in populate_requirement_set wheel_cache=wheel_cache File "/PATH/site-packages/pip/req/req_install.py", line 139, in from_editable editable_req, default_vcs) File "/PATH/site-packages/pip/req/req_install.py", line 1207, in parse_editable req = _build_req_from_url(editable_req) File "/PATH/site-packages/pip/req/req_install.py", line 1103, in _build_req_from_url if parts[-2] in ('tags', 'branches', 'tag', 'branch'): IndexError: list index out of range ``` I'd _meant_ to paste the URL, but it turns out I pasted a newline. Go me. I assume there needs to be a guard on the length of `parts` before seeking the value. ``` > pip -V pip 8.0.3 from /PATH/site-packages (python 2.7) ```
2016-03-04T11:08:34Z
[]
[]
Traceback (most recent call last): File "/PATH/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/PATH/site-packages/pip/commands/install.py", line 287, in run wheel_cache File "/PATH/site-packages/pip/basecommand.py", line 280, in populate_requirement_set wheel_cache=wheel_cache File "/PATH/site-packages/pip/req/req_install.py", line 139, in from_editable editable_req, default_vcs) File "/PATH/site-packages/pip/req/req_install.py", line 1207, in parse_editable req = _build_req_from_url(editable_req) File "/PATH/site-packages/pip/req/req_install.py", line 1103, in _build_req_from_url if parts[-2] in ('tags', 'branches', 'tag', 'branch'): IndexError: list index out of range
17,290
pypa/pip
pypa__pip-3598
ce8999dd0dce4848f109a1b22384ad9050a27998
diff --git a/pip/__init__.py b/pip/__init__.py --- a/pip/__init__.py +++ b/pip/__init__.py @@ -212,7 +212,11 @@ def main(args=None): # Needed for locale.getpreferredencoding(False) to work # in pip.utils.encoding.auto_decode - locale.setlocale(locale.LC_ALL, '') + try: + locale.setlocale(locale.LC_ALL, '') + except locale.Error as e: + # setlocale can apparently crash if locale are uninitialized + logger.debug("Ignoring error %s when setting locale", e) command = commands_dict[cmd_name](isolated=check_isolated(cmd_args)) return command.main(cmd_args)
8.1.1 locale.Error: unsupported locale setting in the Docker container - Pip version: 8.1.1 - Python version: 2.7.6 - Operating System: ubuntu:14.04 in the Docker container ### Description: Traceback after upgrading pip from to 8.1.0 to 8.1.1 when `LC_*` environment variables are empty. ### What I've run: ``` (env) root@cccf5e39dacc:/opt/project# locale -a locale: Cannot set LC_CTYPE to default locale: No such file or directory locale: Cannot set LC_MESSAGES to default locale: No such file or directory locale: Cannot set LC_COLLATE to default locale: No such file or directory C C.UTF-8 POSIX (env) root@cccf5e39dacc:/opt/project# locale locale: Cannot set LC_CTYPE to default locale: No such file or directory locale: Cannot set LC_MESSAGES to default locale: No such file or directory locale: Cannot set LC_ALL to default locale: No such file or directory LANG=en_US.UTF-8 LANGUAGE= LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL= (env) root@cccf5e39dacc:/opt/project# env | grep LC_ (env) root@cccf5e39dacc:/opt/project# pip install pip==8.1.0 Traceback (most recent call last): File "/opt/project/env/bin/pip", line 11, in <module> sys.exit(main()) File "/opt/project/env/local/lib/python2.7/site-packages/pip/__init__.py", line 215, in main locale.setlocale(locale.LC_ALL, '') File "/opt/project/env/lib/python2.7/locale.py", line 579, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting (env) root@cccf5e39dacc:/opt/project# LC_ALL=C pip install pip==8.1.0 Downloading pip-8.1.0-py2.py3-none-any.whl (1.2MB) ``` UPD. I've added this lines into the my Dockerfile to fix locale settings: ``` # Set the locale RUN locale-gen en_US.UTF-8 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en ENV LC_ALL en_US.UTF-8 ``` but traceback still looks like a regression in the `pip` ))
I encountered a similar problem, running on a computer cluster where I don't have admin rights (so can't run locale-gen trivially). I think the exception should be handled somehow, or pip becomes useless. This is introduced by 5589ff286 and can be reproduced with: ``` $ LC_ALL=foo virtualenv/bin/pip list Traceback (most recent call last): File "virtualenv/bin/pip", line 11, in <module> sys.exit(main()) File "virtualenv/local/lib/python2.7/site-packages/pip/__init__.py", line 215, in main locale.setlocale(locale.LC_ALL, '') File "virtualenv/lib/python2.7/locale.py", line 579, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting ``` Also, this is not restricted to docker. @xavfernandez: Could you take a look at this? I've got the same thing on my Raspberry Pi B locale -a output: `C C.UTF-8 en_GB.utf8 en_US.utf8 POSIX ` I'm seeing this on OSX as well, so it is certainly not specific to docker. Interestingly setlocale(3) does document that the empty string is a valid: `the empty string "" (which denotes the native environment)`, and this C code works fine: ``` C #include <locale.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { char* old = setlocale(LC_ALL, ""); if (old==NULL) { printf("Locale setting failed\n"); return 1; } return 0; } ``` But doing the same thing in Python (both 2 and 3) fails: ``` python Python 2.7.11 (default, Mar 31 2016, 15:25:28) [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.setlocale(locale.LC_ALL, '') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/wichert/.pbin/lib/python2.7/locale.py", line 579, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting ``` So possibly this is a Python bug that pip needs to work around. definitely not a docker issue. eg also causing trouble in fresh ubuntu images used with vagrant when locale is not configured on initial provisioning run.
2016-04-03T19:56:42Z
[]
[]
Traceback (most recent call last): File "/opt/project/env/bin/pip", line 11, in <module> sys.exit(main()) File "/opt/project/env/local/lib/python2.7/site-packages/pip/__init__.py", line 215, in main locale.setlocale(locale.LC_ALL, '') File "/opt/project/env/lib/python2.7/locale.py", line 579, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting
17,294
pypa/pip
pypa__pip-3656
fc04667164dd503fc3cbe5d4e16fab6018d7790b
diff --git a/pip/commands/search.py b/pip/commands/search.py --- a/pip/commands/search.py +++ b/pip/commands/search.py @@ -116,12 +116,11 @@ def print_results(hits, name_column_width=None, terminal_width=None): summary = hit['summary'] or '' version = hit.get('versions', ['-'])[-1] if terminal_width is not None: - # wrap and indent summary to fit terminal - summary = textwrap.wrap( - summary, - terminal_width - name_column_width - 5, - ) - summary = ('\n' + ' ' * (name_column_width + 3)).join(summary) + target_width = terminal_width - name_column_width - 5 + if target_width > 10: + # wrap and indent summary to fit terminal + summary = textwrap.wrap(summary, target_width) + summary = ('\n' + ' ' * (name_column_width + 3)).join(summary) line = '%-*s - %s' % (name_column_width, '%s (%s)' % (name, version), summary)
`pip search` doesn't work in narrow terminals - Pip version: 8.1.1 (also happens in at least 8.1.0) - Python version: 2.7.9 - Operating System: xenial ### Description: `pip search` can't print results to narrow terminal windows ### What I've run: `pip search [something with results]` in a 63-column urxvt instance: ``` Exception: Traceback (most recent call last): File "/home/tinruufu/.virtualenvs/tinruufu/local/lib/python2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/home/tinruufu/.virtualenvs/tinruufu/local/lib/python2.7/site-packages/pip/commands/search.py", line 50, in run print_results(hits, terminal_width=terminal_width) File "/home/tinruufu/.virtualenvs/tinruufu/local/lib/python2.7/site-packages/pip/commands/search.py", line 122, in print_results terminal_width - name_column_width - 5, File "/usr/lib/python2.7/textwrap.py", line 354, in wrap return w.wrap(text) File "/usr/lib/python2.7/textwrap.py", line 329, in wrap return self._wrap_chunks(chunks) File "/usr/lib/python2.7/textwrap.py", line 258, in _wrap_chunks raise ValueError("invalid width %r (must be > 0)" % self.width) ValueError: invalid width -14 (must be > 0) ``` ``` $ tput cols 63 ``` as an aside, it's a bummer that the download progress bars don't get narrow in such windows and instead vomits hundreds of lines of rectangles; `progressbar` handles this fine. this is the first time i've found something that just straight-up doesn't work at all though
2016-05-05T13:54:30Z
[]
[]
Traceback (most recent call last): File "/home/tinruufu/.virtualenvs/tinruufu/local/lib/python2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/home/tinruufu/.virtualenvs/tinruufu/local/lib/python2.7/site-packages/pip/commands/search.py", line 50, in run print_results(hits, terminal_width=terminal_width) File "/home/tinruufu/.virtualenvs/tinruufu/local/lib/python2.7/site-packages/pip/commands/search.py", line 122, in print_results terminal_width - name_column_width - 5, File "/usr/lib/python2.7/textwrap.py", line 354, in wrap return w.wrap(text) File "/usr/lib/python2.7/textwrap.py", line 329, in wrap return self._wrap_chunks(chunks) File "/usr/lib/python2.7/textwrap.py", line 258, in _wrap_chunks raise ValueError("invalid width %r (must be > 0)" % self.width) ValueError: invalid width -14 (must be > 0)
17,298
pypa/pip
pypa__pip-3694
5685e0149ac575965105182f7e0e2f5f53392936
diff --git a/pip/commands/install.py b/pip/commands/install.py --- a/pip/commands/install.py +++ b/pip/commands/install.py @@ -352,35 +352,46 @@ def run(self, options, args): if options.target_dir: ensure_dir(options.target_dir) - lib_dir = distutils_scheme('', home=temp_target_dir)['purelib'] - - for item in os.listdir(lib_dir): - target_item_dir = os.path.join(options.target_dir, item) - if os.path.exists(target_item_dir): - if not options.upgrade: - logger.warning( - 'Target directory %s already exists. Specify ' - '--upgrade to force replacement.', - target_item_dir - ) - continue - if os.path.islink(target_item_dir): - logger.warning( - 'Target directory %s already exists and is ' - 'a link. Pip will not automatically replace ' - 'links, please remove if replacement is ' - 'desired.', - target_item_dir - ) - continue - if os.path.isdir(target_item_dir): - shutil.rmtree(target_item_dir) - else: - os.remove(target_item_dir) - - shutil.move( - os.path.join(lib_dir, item), - target_item_dir - ) + # Checking both purelib and platlib directories for installed + # packages to be moved to target directory + lib_dir_list = [] + + purelib_dir = distutils_scheme('', home=temp_target_dir)['purelib'] + platlib_dir = distutils_scheme('', home=temp_target_dir)['platlib'] + + if os.path.exists(purelib_dir): + lib_dir_list.append(purelib_dir) + if os.path.exists(platlib_dir) and platlib_dir != purelib_dir: + lib_dir_list.append(platlib_dir) + + for lib_dir in lib_dir_list: + for item in os.listdir(lib_dir): + target_item_dir = os.path.join(options.target_dir, item) + if os.path.exists(target_item_dir): + if not options.upgrade: + logger.warning( + 'Target directory %s already exists. Specify ' + '--upgrade to force replacement.', + target_item_dir + ) + continue + if os.path.islink(target_item_dir): + logger.warning( + 'Target directory %s already exists and is ' + 'a link. Pip will not automatically replace ' + 'links, please remove if replacement is ' + 'desired.', + target_item_dir + ) + continue + if os.path.isdir(target_item_dir): + shutil.rmtree(target_item_dir) + else: + os.remove(target_item_dir) + + shutil.move( + os.path.join(lib_dir, item), + target_item_dir + ) shutil.rmtree(temp_target_dir) return requirement_set
pip install --target ignores platlib directories - Pip version: 8.1.2 - Python version: 2.7.5 - Operating System: centos7 64 bit ### Description: pip install with --target option has an issue with lib64 packages(platlib). 1) When I tried to install mysql-python using the following command, I ran into an error saying no such file or directory. `pip install --target=/var/tmp/ mysql-python` Issue: The issue is that the package is installed in platlib directory " /tmp/{random_string}/lib64/python " but pip is trying to move files only from purelib directory to target directory but not platlib directory. So it checks for directories under "/tmp/{random_string}/lib/python" and throws exception saying no such file or directory. 2) When I tried to install paramiko==1.16.0 using the following command, I found pycrypto package is missing which is a dependent package for paramiko. `pip install --target=/var/tmp/paramiko paramiko==1.16.0`` Issue: There are three packages (paramiko, ecdsa, pycrypto) that are installed in /tmp/{random_string} directory. paramiko and ecdsa are installed in purelib "/tmp/{random_string}/lib/python" and pycrypto is installed in platlib "/tmp/{random_string}/lib64/python" which is expected based on system architecture. But pip moves files under purelib to target directory but not files under platlib, as a result pycrypto packages in missing. Moreover the success message says "Successfully installed ecdsa-0.13 paramiko-1.16.0 pycrypto-2.6.1" ### What I've run: `pip install --target=/var/tmp/ mysql-python` ``` Exception: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 368, in run for item in os.listdir(lib_dir): OSError: [Errno 2] No such file or directory: '/tmp/tmpbtxE72/lib/python' ``` ``` pip install --target=/var/tmp/paramiko paramiko==1.16.0 ``` ``` Collecting paramiko==1.16.0 Using cached paramiko-1.16.0-py2.py3-none-any.whl Collecting ecdsa>=0.11 (from paramiko==1.16.0) Using cached ecdsa-0.13-py2.py3-none-any.whl Collecting pycrypto!=2.4,>=2.1 (from paramiko==1.16.0) Using cached pycrypto-2.6.1.tar.gz Installing collected packages: ecdsa, pycrypto, paramiko Running setup.py install for pycrypto ... done Successfully installed ecdsa-0.13 paramiko-1.16.0 pycrypto-2.6.1 ``` ### Note: I'm planning to fix this and raise a pull request so that pip considers both purelib as well as platlib (if both are different and exists)
2016-05-19T11:59:04Z
[]
[]
Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 368, in run for item in os.listdir(lib_dir): OSError: [Errno 2] No such file or directory: '/tmp/tmpbtxE72/lib/python'
17,299
pypa/pip
pypa__pip-3794
218fe03db5076025bb8e0c017c559d9e68e354c5
diff --git a/pip/wheel.py b/pip/wheel.py --- a/pip/wheel.py +++ b/pip/wheel.py @@ -298,9 +298,8 @@ def clobber(source, dest, is_base, fixer=None, filter=None): continue elif (is_base and s.endswith('.dist-info') and - # is self.req.project_name case preserving? - s.lower().startswith( - req.name.replace('-', '_').lower())): + canonicalize_name(s).startswith( + canonicalize_name(req.name))): assert not info_dir, ('Multiple .dist-info directories: ' + destsubdir + ', ' + ', '.join(info_dir))
Installing package with period in name (normalized to a hyphen) fails on 8.1.2 - Pip version: 8.1.2 - Python version: 2.7.9 - Operating System: OS X 10.11.5 ### Description: Package `github3.py` has a name that should be normalized to `github3-py` and is when you view it on pypi.io. If I then tell pip to install the hyphenated name, I get an exception. ### What I've run: ``` $ pip install -i https://pypi.io/simple github3-py ``` This results in an installed package but an error: ``` Exception: Traceback (most recent call last): File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/req/req_set.py", line 742, in install **kwargs File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/req/req_install.py", line 831, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/req/req_install.py", line 1032, in move_wheel_files isolated=self.isolated, File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/wheel.py", line 348, in move_wheel_files assert info_dir, "%s .dist-info directory not found" % req AssertionError: github3-py .dist-info directory not found ``` If I then try using `github3.py` I see that the package is installed: ``` $ pip install -i https://pypi.io/simple github3.py Requirement already satisfied (use --upgrade to upgrade): github3.py in ./.test/lib/python2.7/site-packages Requirement already satisfied (use --upgrade to upgrade): uritemplate.py>=0.2.0 in ./.test/lib/python2.7/site-packages (from github3.py) Requirement already satisfied (use --upgrade to upgrade): requests>=2.0 in ./.test/lib/python2.7/site-packages (from github3.py) ```
2016-06-12T20:23:27Z
[]
[]
Traceback (most recent call last): File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/req/req_set.py", line 742, in install **kwargs File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/req/req_install.py", line 831, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/req/req_install.py", line 1032, in move_wheel_files isolated=self.isolated, File "/Users/sigmavirus24/.test/lib/python2.7/site-packages/pip/wheel.py", line 348, in move_wheel_files assert info_dir, "%s .dist-info directory not found" % req AssertionError: github3-py .dist-info directory not found
17,304
pypa/pip
pypa__pip-392
d40c502bde4859aa3016a0aa009e4fb9cb229535
diff --git a/pip/commands/freeze.py b/pip/commands/freeze.py --- a/pip/commands/freeze.py +++ b/pip/commands/freeze.py @@ -85,7 +85,9 @@ def run(self, options, args): elif (line.startswith('-r') or line.startswith('--requirement') or line.startswith('-Z') or line.startswith('--always-unzip') or line.startswith('-f') or line.startswith('-i') - or line.startswith('--extra-index-url')): + or line.startswith('--extra-index-url') + or line.startswith('--find-links') + or line.startswith('--index-url')): f.write(line) continue else:
"pip freeze -r" returns ValueError() if requirements file contains --find-links It seems that pip freeze should not pass --find-links or --index-url to distribute/setuptools when inlined in a requirements file. Here is an easy way to repro the problem: 1) echo "--find-links http://foo.bar/" > /tmp/req.txt 2) pip freeze -r /tmp/req.txt """ Exception: Traceback (most recent call last): File "/Users/hpfennig/work/pip/pip/basecommand.py", line 95, in main self.run(options, args) File "/Users/hpfennig/work/pip/pip/commands/freeze.py", line 92, in run line_req = InstallRequirement.from_line(line) File "/Users/hpfennig/work/pip/pip/req.py", line 105, in from_line return cls(req, comes_from, url=url) File "/Users/hpfennig/work/pip/pip/req.py", line 39, in **init** req = pkg_resources.Requirement.parse(req) File "/Users/hpfennig/.virtualenvs/pip-bug-virt-env/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2510, in parse reqs = list(parse_requirements(s)) File "/Users/hpfennig/.virtualenvs/pip-bug-virt-env/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2436, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "/Users/hpfennig/.virtualenvs/pip-bug-virt-env/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2404, in scan_list raise ValueError("Expected "+item_name+" in",line,"at",line[p:]) ValueError: ('Expected version spec in', '--find-links http://foo.bar/', 'at', ' http://foo.bar/') Storing complete log in /Users/hpfennig/.pip/pip.log """ I have a fix, but I am not sure this is the correct way to go about it. Would be happy to do an official pull request if needed. diff --git a/pip/commands/freeze.py b/pip/commands/freeze.py index 01b5df9..03ac80f 100644 --- a/pip/commands/freeze.py +++ b/pip/commands/freeze.py @@ -85,7 +85,9 @@ class FreezeCommand(Command): elif (line.startswith('-r') or line.startswith('--requirement') or line.startswith('-Z') or line.startswith('--always-unzip') or line.startswith('-f') or line.startswith('-i') - or line.startswith('--extra-index-url')): - or line.startswith('--extra-index-url') - or line.startswith('--find-links') - or line.startswith('--index-url')): f.write(line) continue else:
Yep, that fix looks correct - thanks for the report! A pull request (with a test; should be easy to follow other examples in test_freeze.py) would be great - otherwise I'll get to it when I can.
2011-12-04T06:16:09Z
[]
[]
Traceback (most recent call last): File "/Users/hpfennig/work/pip/pip/basecommand.py", line 95, in main self.run(options, args) File "/Users/hpfennig/work/pip/pip/commands/freeze.py", line 92, in run line_req = InstallRequirement.from_line(line) File "/Users/hpfennig/work/pip/pip/req.py", line 105, in from_line return cls(req, comes_from, url=url) File "/Users/hpfennig/work/pip/pip/req.py", line 39, in **init** req = pkg_resources.Requirement.parse(req) File "/Users/hpfennig/.virtualenvs/pip-bug-virt-env/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2510, in parse reqs = list(parse_requirements(s)) File "/Users/hpfennig/.virtualenvs/pip-bug-virt-env/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2436, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "/Users/hpfennig/.virtualenvs/pip-bug-virt-env/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/pkg_resources.py", line 2404, in scan_list raise ValueError("Expected "+item_name+" in",line,"at",line[p:]) ValueError: ('Expected version spec in', '--find-links http://foo.bar/', 'at', ' http://foo.bar/')
17,308
pypa/pip
pypa__pip-4038
22f2e01be5cd64d7db524e1ab5931fdc98521cfb
diff --git a/pip/_vendor/cachecontrol/__init__.py b/pip/_vendor/cachecontrol/__init__.py --- a/pip/_vendor/cachecontrol/__init__.py +++ b/pip/_vendor/cachecontrol/__init__.py @@ -4,7 +4,7 @@ """ __author__ = 'Eric Larson' __email__ = 'eric@ionrock.org' -__version__ = '0.11.6' +__version__ = '0.11.7' from .wrapper import CacheControl from .adapter import CacheControlAdapter diff --git a/pip/_vendor/cachecontrol/adapter.py b/pip/_vendor/cachecontrol/adapter.py --- a/pip/_vendor/cachecontrol/adapter.py +++ b/pip/_vendor/cachecontrol/adapter.py @@ -1,3 +1,4 @@ +import types import functools from pip._vendor.requests.adapters import HTTPAdapter @@ -55,6 +56,10 @@ def build_response(self, request, response, from_cache=False): cached response """ if not from_cache and request.method == 'GET': + # Check for any heuristics that might update headers + # before trying to cache. + if self.heuristic: + response = self.heuristic.apply(response) # apply any expiration heuristics if response.status == 304: @@ -82,11 +87,6 @@ def build_response(self, request, response, from_cache=False): elif response.status == 301: self.controller.cache_response(request, response) else: - # Check for any heuristics that might update headers - # before trying to cache. - if self.heuristic: - response = self.heuristic.apply(response) - # Wrap the response file with a wrapper that will cache the # response when the stream has been consumed. response._fp = CallbackFileWrapper( @@ -97,6 +97,14 @@ def build_response(self, request, response, from_cache=False): response, ) ) + if response.chunked: + super_update_chunk_length = response._update_chunk_length + + def _update_chunk_length(self): + super_update_chunk_length() + if self.chunk_left == 0: + self._fp._close() + response._update_chunk_length = types.MethodType(_update_chunk_length, response) resp = super(CacheControlAdapter, self).build_response( request, response diff --git a/pip/_vendor/cachecontrol/controller.py b/pip/_vendor/cachecontrol/controller.py --- a/pip/_vendor/cachecontrol/controller.py +++ b/pip/_vendor/cachecontrol/controller.py @@ -290,7 +290,7 @@ def cache_response(self, request, response, body=None): elif 'date' in response_headers: # cache when there is a max-age > 0 if cc and cc.get('max-age'): - if int(cc['max-age']) > 0: + if cc['max-age'].isdigit() and int(cc['max-age']) > 0: logger.debug('Caching b/c date exists and max-age > 0') self.cache.set( cache_url, diff --git a/pip/_vendor/cachecontrol/filewrapper.py b/pip/_vendor/cachecontrol/filewrapper.py --- a/pip/_vendor/cachecontrol/filewrapper.py +++ b/pip/_vendor/cachecontrol/filewrapper.py @@ -45,19 +45,34 @@ def __is_fp_closed(self): # TODO: Add some logging here... return False + def _close(self): + if self.__callback: + self.__callback(self.__buf.getvalue()) + + # We assign this to None here, because otherwise we can get into + # really tricky problems where the CPython interpreter dead locks + # because the callback is holding a reference to something which + # has a __del__ method. Setting this to None breaks the cycle + # and allows the garbage collector to do it's thing normally. + self.__callback = None + def read(self, amt=None): data = self.__fp.read(amt) self.__buf.write(data) + if self.__is_fp_closed(): + self._close() + return data + + def _safe_read(self, amt): + data = self.__fp._safe_read(amt) + if amt == 2 and data == b'\r\n': + # urllib executes this read to toss the CRLF at the end + # of the chunk. + return data + + self.__buf.write(data) if self.__is_fp_closed(): - if self.__callback: - self.__callback(self.__buf.getvalue()) - - # We assign this to None here, because otherwise we can get into - # really tricky problems where the CPython interpreter dead locks - # because the callback is holding a reference to something which - # has a __del__ method. Setting this to None breaks the cycle - # and allows the garbage collector to do it's thing normally. - self.__callback = None + self._close() return data diff --git a/pip/_vendor/cachecontrol/serialize.py b/pip/_vendor/cachecontrol/serialize.py --- a/pip/_vendor/cachecontrol/serialize.py +++ b/pip/_vendor/cachecontrol/serialize.py @@ -134,6 +134,12 @@ def prepare_response(self, request, cached): body_raw = cached["response"].pop("body") + headers = CaseInsensitiveDict(data=cached['response']['headers']) + if headers.get('transfer-encoding', '') == 'chunked': + headers.pop('transfer-encoding') + + cached['response']['headers'] = headers + try: body = io.BytesIO(body_raw) except TypeError: diff --git a/pip/_vendor/distlib/__init__.py b/pip/_vendor/distlib/__init__.py --- a/pip/_vendor/distlib/__init__.py +++ b/pip/_vendor/distlib/__init__.py @@ -6,7 +6,7 @@ # import logging -__version__ = '0.2.3' +__version__ = '0.2.4' class DistlibException(Exception): pass diff --git a/pip/_vendor/distlib/_backport/shutil.py b/pip/_vendor/distlib/_backport/shutil.py --- a/pip/_vendor/distlib/_backport/shutil.py +++ b/pip/_vendor/distlib/_backport/shutil.py @@ -55,8 +55,8 @@ class ReadError(EnvironmentError): """Raised when an archive cannot be read""" class RegistryError(Exception): - """Raised when a registery operation with the archiving - and unpacking registeries fails""" + """Raised when a registry operation with the archiving + and unpacking registries fails""" try: @@ -648,7 +648,7 @@ def register_unpack_format(name, extensions, function, extra_args=None, _UNPACK_FORMATS[name] = extensions, function, extra_args, description def unregister_unpack_format(name): - """Removes the pack format from the registery.""" + """Removes the pack format from the registry.""" del _UNPACK_FORMATS[name] def _ensure_directory(path): diff --git a/pip/_vendor/distlib/_backport/tarfile.py b/pip/_vendor/distlib/_backport/tarfile.py --- a/pip/_vendor/distlib/_backport/tarfile.py +++ b/pip/_vendor/distlib/_backport/tarfile.py @@ -331,7 +331,7 @@ class ExtractError(TarError): """General exception for extract errors.""" pass class ReadError(TarError): - """Exception for unreadble tar archives.""" + """Exception for unreadable tar archives.""" pass class CompressionError(TarError): """Exception for unavailable compression methods.""" diff --git a/pip/_vendor/distlib/compat.py b/pip/_vendor/distlib/compat.py --- a/pip/_vendor/distlib/compat.py +++ b/pip/_vendor/distlib/compat.py @@ -10,6 +10,11 @@ import re import sys +try: + import ssl +except ImportError: + ssl = None + if sys.version_info[0] < 3: # pragma: no cover from StringIO import StringIO string_types = basestring, @@ -30,8 +35,10 @@ def quote(s): import urllib2 from urllib2 import (Request, urlopen, URLError, HTTPError, HTTPBasicAuthHandler, HTTPPasswordMgr, - HTTPSHandler, HTTPHandler, HTTPRedirectHandler, + HTTPHandler, HTTPRedirectHandler, build_opener) + if ssl: + from urllib2 import HTTPSHandler import httplib import xmlrpclib import Queue as queue @@ -66,8 +73,10 @@ def splituser(host): from urllib.request import (urlopen, urlretrieve, Request, url2pathname, pathname2url, HTTPBasicAuthHandler, HTTPPasswordMgr, - HTTPSHandler, HTTPHandler, HTTPRedirectHandler, + HTTPHandler, HTTPRedirectHandler, build_opener) + if ssl: + from urllib.request import HTTPSHandler from urllib.error import HTTPError, URLError, ContentTooShortError import http.client as httplib import urllib.request as urllib2 @@ -101,7 +110,7 @@ def _dnsname_match(dn, hostname, max_wildcards=1): wildcards = leftmost.count('*') if wildcards > max_wildcards: # Issue #17980: avoid denials of service by refusing more - # than one wildcard per fragment. A survery of established + # than one wildcard per fragment. A survey of established # policy among SSL implementations showed it to be a # reasonable choice. raise CertificateError( @@ -366,7 +375,7 @@ def _get_normal_name(orig_enc): def detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should - be used to decode a Python source file. It requires one argment, readline, + be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used diff --git a/pip/_vendor/distlib/database.py b/pip/_vendor/distlib/database.py --- a/pip/_vendor/distlib/database.py +++ b/pip/_vendor/distlib/database.py @@ -1308,5 +1308,5 @@ def make_dist(name, version, **kwargs): md = Metadata(**kwargs) md.name = name md.version = version - md.summary = summary or 'Plaeholder for summary' + md.summary = summary or 'Placeholder for summary' return Distribution(md) diff --git a/pip/_vendor/distlib/index.py b/pip/_vendor/distlib/index.py --- a/pip/_vendor/distlib/index.py +++ b/pip/_vendor/distlib/index.py @@ -51,7 +51,9 @@ def __init__(self, url=None): self.gpg_home = None self.rpc_proxy = None with open(os.devnull, 'w') as sink: - for s in ('gpg2', 'gpg'): + # Use gpg by default rather than gpg2, as gpg2 insists on + # prompting for passwords + for s in ('gpg', 'gpg2'): try: rc = subprocess.check_call([s, '--version'], stdout=sink, stderr=sink) @@ -74,7 +76,7 @@ def _get_pypirc_command(self): def read_configuration(self): """ Read the PyPI access configuration as supported by distutils, getting - PyPI to do the acutal work. This populates ``username``, ``password``, + PyPI to do the actual work. This populates ``username``, ``password``, ``realm`` and ``url`` attributes from the configuration. """ # get distutils to do the work @@ -276,7 +278,7 @@ def upload_file(self, metadata, filename, signer=None, sign_password=None, sha256_digest = hashlib.sha256(file_data).hexdigest() d.update({ ':action': 'file_upload', - 'protcol_version': '1', + 'protocol_version': '1', 'filetype': filetype, 'pyversion': pyversion, 'md5_digest': md5_digest, diff --git a/pip/_vendor/distlib/locators.py b/pip/_vendor/distlib/locators.py --- a/pip/_vendor/distlib/locators.py +++ b/pip/_vendor/distlib/locators.py @@ -21,13 +21,13 @@ from . import DistlibException from .compat import (urljoin, urlparse, urlunparse, url2pathname, pathname2url, queue, quote, unescape, string_types, build_opener, - HTTPRedirectHandler as BaseRedirectHandler, + HTTPRedirectHandler as BaseRedirectHandler, text_type, Request, HTTPError, URLError) from .database import Distribution, DistributionPath, make_dist from .metadata import Metadata from .util import (cached_property, parse_credentials, ensure_slash, split_filename, get_project_data, parse_requirement, - parse_name_and_version, ServerProxy) + parse_name_and_version, ServerProxy, normalize_name) from .version import get_scheme, UnsupportedVersionError from .wheel import Wheel, is_compatible @@ -113,6 +113,28 @@ def __init__(self, scheme='default'): # is set from the requirement passed to locate(). See issue #18 for # why this can be useful to know. self.matcher = None + self.errors = queue.Queue() + + def get_errors(self): + """ + Return any errors which have occurred. + """ + result = [] + while not self.errors.empty(): # pragma: no cover + try: + e = self.errors.get(False) + result.append(e) + except self.errors.Empty: + continue + self.errors.task_done() + return result + + def clear_errors(self): + """ + Clear any errors which may have been logged. + """ + # Just get the errors and throw them away + self.get_errors() def clear_cache(self): self._cache.clear() @@ -155,6 +177,7 @@ def get_project(self, name): elif name in self._cache: result = self._cache[name] else: + self.clear_errors() result = self._get_project(name) self._cache[name] = result return result @@ -210,14 +233,7 @@ def convert_url_to_download_info(self, url, project_name): "filename" and "url"; otherwise, None is returned. """ def same_project(name1, name2): - name1, name2 = name1.lower(), name2.lower() - if name1 == name2: - result = True - else: - # distribute replaces '-' by '_' in project names, so it - # can tell where the version starts in a filename. - result = name1.replace('_', '-') == name2.replace('_', '-') - return result + return normalize_name(name1) == normalize_name(name2) result = None scheme, netloc, path, params, query, frag = urlparse(url) @@ -250,7 +266,7 @@ def same_project(name1, name2): 'python-version': ', '.join( ['.'.join(list(v[2:])) for v in wheel.pyver]), } - except Exception as e: + except Exception as e: # pragma: no cover logger.warning('invalid path for wheel: %s', path) elif path.endswith(self.downloadable_extensions): path = filename = posixpath.basename(path) @@ -489,6 +505,7 @@ def _get_project(self, name): # result['urls'].setdefault(md.version, set()).add(url) # result['digests'][url] = self._get_digest(info) except Exception as e: + self.errors.put(text_type(e)) logger.exception('JSON fetch failed: %s', e) return result @@ -714,6 +731,8 @@ def _fetch(self): self._should_queue(link, url, rel)): logger.debug('Queueing %s from %s', link, url) self._to_fetch.put(link) + except Exception as e: # pragma: no cover + self.errors.put(text_type(e)) finally: # always do this, to avoid hangs :-) self._to_fetch.task_done() diff --git a/pip/_vendor/distlib/manifest.py b/pip/_vendor/distlib/manifest.py --- a/pip/_vendor/distlib/manifest.py +++ b/pip/_vendor/distlib/manifest.py @@ -12,6 +12,7 @@ import logging import os import re +import sys from . import DistlibException from .compat import fsdecode @@ -26,6 +27,12 @@ _COLLAPSE_PATTERN = re.compile('\\\w*\n', re.M) _COMMENTED_LINE = re.compile('#.*?(?=\n)|\n(?=$)', re.M | re.S) +# +# Due to the different results returned by fnmatch.translate, we need +# to do slightly different processing for Python 2.7 and 3.2 ... this needed +# to be brought in for Python 3.6 onwards. +# +_PYTHON_VERSION = sys.version_info[:2] class Manifest(object): """A list of files built by on exploring the filesystem and filtered by @@ -322,24 +329,43 @@ def _translate_pattern(self, pattern, anchor=True, prefix=None, else: return pattern + if _PYTHON_VERSION > (3, 2): + # ditch start and end characters + start, _, end = self._glob_to_re('_').partition('_') + if pattern: pattern_re = self._glob_to_re(pattern) + if _PYTHON_VERSION > (3, 2): + assert pattern_re.startswith(start) and pattern_re.endswith(end) else: pattern_re = '' base = re.escape(os.path.join(self.base, '')) if prefix is not None: # ditch end of pattern character - empty_pattern = self._glob_to_re('') - prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)] + if _PYTHON_VERSION <= (3, 2): + empty_pattern = self._glob_to_re('') + prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)] + else: + prefix_re = self._glob_to_re(prefix) + assert prefix_re.startswith(start) and prefix_re.endswith(end) + prefix_re = prefix_re[len(start): len(prefix_re) - len(end)] sep = os.sep if os.sep == '\\': sep = r'\\' - pattern_re = '^' + base + sep.join((prefix_re, - '.*' + pattern_re)) - else: # no prefix -- respect anchor flag + if _PYTHON_VERSION <= (3, 2): + pattern_re = '^' + base + sep.join((prefix_re, + '.*' + pattern_re)) + else: + pattern_re = pattern_re[len(start): len(pattern_re) - len(end)] + pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep, + pattern_re, end) + else: # no prefix -- respect anchor flag if anchor: - pattern_re = '^' + base + pattern_re + if _PYTHON_VERSION <= (3, 2): + pattern_re = '^' + base + pattern_re + else: + pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):]) return re.compile(pattern_re) diff --git a/pip/_vendor/distlib/metadata.py b/pip/_vendor/distlib/metadata.py --- a/pip/_vendor/distlib/metadata.py +++ b/pip/_vendor/distlib/metadata.py @@ -444,16 +444,16 @@ def set(self, name, value): # check that the values are valid if not scheme.is_valid_matcher(v.split(';')[0]): logger.warning( - '%r: %r is not valid (field %r)', + "'%s': '%s' is not valid (field '%s')", project_name, v, name) # FIXME this rejects UNKNOWN, is that right? elif name in _VERSIONS_FIELDS and value is not None: if not scheme.is_valid_constraint_list(value): - logger.warning('%r: %r is not a valid version (field %r)', + logger.warning("'%s': '%s' is not a valid version (field '%s')", project_name, value, name) elif name in _VERSION_FIELDS and value is not None: if not scheme.is_valid_version(value): - logger.warning('%r: %r is not a valid version (field %r)', + logger.warning("'%s': '%s' is not a valid version (field '%s')", project_name, value, name) if name in _UNICODEFIELDS: @@ -531,7 +531,7 @@ def are_valid_constraints(value): for field in fields: value = self.get(field, None) if value is not None and not controller(value): - warnings.append('Wrong value for %r: %s' % (field, value)) + warnings.append("Wrong value for '%s': %s" % (field, value)) return missing, warnings @@ -766,6 +766,8 @@ def __getattribute__(self, key): result = d.get(key, value) else: d = d.get('python.exports') + if not d: + d = self._data.get('python.exports') if d: result = d.get(key, value) if result is sentinel: @@ -784,8 +786,8 @@ def _validate_value(self, key, value, scheme=None): if (scheme or self.scheme) not in exclusions: m = pattern.match(value) if not m: - raise MetadataInvalidError('%r is an invalid value for ' - 'the %r property' % (value, + raise MetadataInvalidError("'%s' is an invalid value for " + "the '%s' property" % (value, key)) def __setattr__(self, key, value): diff --git a/pip/_vendor/distlib/resources.py b/pip/_vendor/distlib/resources.py --- a/pip/_vendor/distlib/resources.py +++ b/pip/_vendor/distlib/resources.py @@ -289,9 +289,14 @@ def _is_directory(self, path): } try: - import _frozen_importlib - _finder_registry[_frozen_importlib.SourceFileLoader] = ResourceFinder - _finder_registry[_frozen_importlib.FileFinder] = ResourceFinder + # In Python 3.6, _frozen_importlib -> _frozen_importlib_external + try: + import _frozen_importlib_external as _fi + except ImportError: + import _frozen_importlib as _fi + _finder_registry[_fi.SourceFileLoader] = ResourceFinder + _finder_registry[_fi.FileFinder] = ResourceFinder + del _fi except (ImportError, AttributeError): pass diff --git a/pip/_vendor/distlib/scripts.py b/pip/_vendor/distlib/scripts.py --- a/pip/_vendor/distlib/scripts.py +++ b/pip/_vendor/distlib/scripts.py @@ -52,7 +52,7 @@ def _resolve(module, func): return result try: - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) func = _resolve('%(module)s', '%(func)s') rc = func() # None interpreted as 0 diff --git a/pip/_vendor/distlib/util.py b/pip/_vendor/distlib/util.py --- a/pip/_vendor/distlib/util.py +++ b/pip/_vendor/distlib/util.py @@ -15,7 +15,10 @@ import re import shutil import socket -import ssl +try: + import ssl +except ImportError: # pragma: no cover + ssl = None import subprocess import sys import tarfile @@ -24,17 +27,16 @@ try: import threading -except ImportError: +except ImportError: # pragma: no cover import dummy_threading as threading import time from . import DistlibException from .compat import (string_types, text_type, shutil, raw_input, StringIO, cache_from_source, urlopen, urljoin, httplib, xmlrpclib, - splittype, HTTPHandler, HTTPSHandler as BaseHTTPSHandler, - BaseConfigurator, valid_ident, Container, configparser, - URLError, match_hostname, CertificateError, ZipFile, - fsdecode) + splittype, HTTPHandler, BaseConfigurator, valid_ident, + Container, configparser, URLError, ZipFile, fsdecode, + unquote) logger = logging.getLogger(__name__) @@ -540,7 +542,7 @@ def __init__(self, name, prefix, suffix, flags): def value(self): return resolve(self.prefix, self.suffix) - def __repr__(self): + def __repr__(self): # pragma: no cover return '<ExportEntry %s = %s:%s %s>' % (self.name, self.prefix, self.suffix, self.flags) @@ -567,8 +569,8 @@ def get_export_entry(specification): if not m: result = None if '[' in specification or ']' in specification: - raise DistlibException('Invalid specification ' - '%r' % specification) + raise DistlibException("Invalid specification " + "'%s'" % specification) else: d = m.groupdict() name = d['name'] @@ -578,14 +580,14 @@ def get_export_entry(specification): prefix, suffix = path, None else: if colons != 1: - raise DistlibException('Invalid specification ' - '%r' % specification) + raise DistlibException("Invalid specification " + "'%s'" % specification) prefix, suffix = path.split(':') flags = d['flags'] if flags is None: if '[' in specification or ']' in specification: - raise DistlibException('Invalid specification ' - '%r' % specification) + raise DistlibException("Invalid specification " + "'%s'" % specification) flags = [] else: flags = [f.strip() for f in flags.split(',')] @@ -696,6 +698,7 @@ def split_filename(filename, project_name=None): """ result = None pyver = None + filename = unquote(filename).replace(' ', '-') m = PYTHON_VERSION.search(filename) if m: pyver = m.group(1) @@ -804,7 +807,7 @@ def __init__(self, base): """ # we use 'isdir' instead of 'exists', because we want to # fail if there's a file with that name - if not os.path.isdir(base): + if not os.path.isdir(base): # pragma: no cover os.makedirs(base) if (os.stat(base).st_mode & 0o77) != 0: logger.warning('Directory \'%s\' is not private', base) @@ -940,12 +943,12 @@ def remove(self, pred, succ): try: preds = self._preds[succ] succs = self._succs[pred] - except KeyError: + except KeyError: # pragma: no cover raise ValueError('%r not a successor of anything' % succ) try: preds.remove(pred) succs.remove(succ) - except KeyError: + except KeyError: # pragma: no cover raise ValueError('%r not a successor of %r' % (succ, pred)) def is_step(self, step): @@ -1071,7 +1074,7 @@ def check_path(path): elif archive_filename.endswith('.tar'): format = 'tar' mode = 'r' - else: + else: # pragma: no cover raise ValueError('Unknown format for %r' % archive_filename) try: if format == 'zip': @@ -1257,99 +1260,102 @@ def _iglob(path_glob): for fn in _iglob(os.path.join(path, radical)): yield fn +if ssl: + from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname, + CertificateError) # # HTTPSConnection which verifies certificates/matches domains # -class HTTPSConnection(httplib.HTTPSConnection): - ca_certs = None # set this to the path to the certs file (.pem) - check_domain = True # only used if ca_certs is not None - - # noinspection PyPropertyAccess - def connect(self): - sock = socket.create_connection((self.host, self.port), self.timeout) - if getattr(self, '_tunnel_host', False): - self.sock = sock - self._tunnel() - - if not hasattr(ssl, 'SSLContext'): - # For 2.x - if self.ca_certs: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, - cert_reqs=cert_reqs, - ssl_version=ssl.PROTOCOL_SSLv23, - ca_certs=self.ca_certs) - else: - context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) - context.options |= ssl.OP_NO_SSLv2 - if self.cert_file: - context.load_cert_chain(self.cert_file, self.key_file) - kwargs = {} + class HTTPSConnection(httplib.HTTPSConnection): + ca_certs = None # set this to the path to the certs file (.pem) + check_domain = True # only used if ca_certs is not None + + # noinspection PyPropertyAccess + def connect(self): + sock = socket.create_connection((self.host, self.port), self.timeout) + if getattr(self, '_tunnel_host', False): + self.sock = sock + self._tunnel() + + if not hasattr(ssl, 'SSLContext'): + # For 2.x + if self.ca_certs: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, + cert_reqs=cert_reqs, + ssl_version=ssl.PROTOCOL_SSLv23, + ca_certs=self.ca_certs) + else: # pragma: no cover + context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) + context.options |= ssl.OP_NO_SSLv2 + if self.cert_file: + context.load_cert_chain(self.cert_file, self.key_file) + kwargs = {} + if self.ca_certs: + context.verify_mode = ssl.CERT_REQUIRED + context.load_verify_locations(cafile=self.ca_certs) + if getattr(ssl, 'HAS_SNI', False): + kwargs['server_hostname'] = self.host + self.sock = context.wrap_socket(sock, **kwargs) + if self.ca_certs and self.check_domain: + try: + match_hostname(self.sock.getpeercert(), self.host) + logger.debug('Host verified: %s', self.host) + except CertificateError: # pragma: no cover + self.sock.shutdown(socket.SHUT_RDWR) + self.sock.close() + raise + + class HTTPSHandler(BaseHTTPSHandler): + def __init__(self, ca_certs, check_domain=True): + BaseHTTPSHandler.__init__(self) + self.ca_certs = ca_certs + self.check_domain = check_domain + + def _conn_maker(self, *args, **kwargs): + """ + This is called to create a connection instance. Normally you'd + pass a connection class to do_open, but it doesn't actually check for + a class, and just expects a callable. As long as we behave just as a + constructor would have, we should be OK. If it ever changes so that + we *must* pass a class, we'll create an UnsafeHTTPSConnection class + which just sets check_domain to False in the class definition, and + choose which one to pass to do_open. + """ + result = HTTPSConnection(*args, **kwargs) if self.ca_certs: - context.verify_mode = ssl.CERT_REQUIRED - context.load_verify_locations(cafile=self.ca_certs) - if getattr(ssl, 'HAS_SNI', False): - kwargs['server_hostname'] = self.host - self.sock = context.wrap_socket(sock, **kwargs) - if self.ca_certs and self.check_domain: - try: - match_hostname(self.sock.getpeercert(), self.host) - logger.debug('Host verified: %s', self.host) - except CertificateError: - self.sock.shutdown(socket.SHUT_RDWR) - self.sock.close() - raise - -class HTTPSHandler(BaseHTTPSHandler): - def __init__(self, ca_certs, check_domain=True): - BaseHTTPSHandler.__init__(self) - self.ca_certs = ca_certs - self.check_domain = check_domain - - def _conn_maker(self, *args, **kwargs): - """ - This is called to create a connection instance. Normally you'd - pass a connection class to do_open, but it doesn't actually check for - a class, and just expects a callable. As long as we behave just as a - constructor would have, we should be OK. If it ever changes so that - we *must* pass a class, we'll create an UnsafeHTTPSConnection class - which just sets check_domain to False in the class definition, and - choose which one to pass to do_open. - """ - result = HTTPSConnection(*args, **kwargs) - if self.ca_certs: - result.ca_certs = self.ca_certs - result.check_domain = self.check_domain - return result - - def https_open(self, req): - try: - return self.do_open(self._conn_maker, req) - except URLError as e: - if 'certificate verify failed' in str(e.reason): - raise CertificateError('Unable to verify server certificate ' - 'for %s' % req.host) - else: - raise + result.ca_certs = self.ca_certs + result.check_domain = self.check_domain + return result -# -# To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The- -# Middle proxy using HTTP listens on port 443, or an index mistakenly serves -# HTML containing a http://xyz link when it should be https://xyz), -# you can use the following handler class, which does not allow HTTP traffic. -# -# It works by inheriting from HTTPHandler - so build_opener won't add a -# handler for HTTP itself. -# -class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler): - def http_open(self, req): - raise URLError('Unexpected HTTP request on what should be a secure ' - 'connection: %s' % req) + def https_open(self, req): + try: + return self.do_open(self._conn_maker, req) + except URLError as e: + if 'certificate verify failed' in str(e.reason): + raise CertificateError('Unable to verify server certificate ' + 'for %s' % req.host) + else: + raise + + # + # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The- + # Middle proxy using HTTP listens on port 443, or an index mistakenly serves + # HTML containing a http://xyz link when it should be https://xyz), + # you can use the following handler class, which does not allow HTTP traffic. + # + # It works by inheriting from HTTPHandler - so build_opener won't add a + # handler for HTTP itself. + # + class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler): + def http_open(self, req): + raise URLError('Unexpected HTTP request on what should be a secure ' + 'connection: %s' % req) # # XML-RPC with timeouts @@ -1365,11 +1371,12 @@ def __init__(self, host='', port=None, **kwargs): self._setup(self._connection_class(host, port, **kwargs)) - class HTTPS(httplib.HTTPS): - def __init__(self, host='', port=None, **kwargs): - if port == 0: # 0 means use port 0, not the default port - port = None - self._setup(self._connection_class(host, port, **kwargs)) + if ssl: + class HTTPS(httplib.HTTPS): + def __init__(self, host='', port=None, **kwargs): + if port == 0: # 0 means use port 0, not the default port + port = None + self._setup(self._connection_class(host, port, **kwargs)) class Transport(xmlrpclib.Transport): @@ -1388,25 +1395,26 @@ def make_connection(self, host): result = self._connection[1] return result -class SafeTransport(xmlrpclib.SafeTransport): - def __init__(self, timeout, use_datetime=0): - self.timeout = timeout - xmlrpclib.SafeTransport.__init__(self, use_datetime) - - def make_connection(self, host): - h, eh, kwargs = self.get_host_info(host) - if not kwargs: - kwargs = {} - kwargs['timeout'] = self.timeout - if _ver_info == (2, 6): - result = HTTPS(host, None, **kwargs) - else: - if not self._connection or host != self._connection[0]: - self._extra_headers = eh - self._connection = host, httplib.HTTPSConnection(h, None, - **kwargs) - result = self._connection[1] - return result +if ssl: + class SafeTransport(xmlrpclib.SafeTransport): + def __init__(self, timeout, use_datetime=0): + self.timeout = timeout + xmlrpclib.SafeTransport.__init__(self, use_datetime) + + def make_connection(self, host): + h, eh, kwargs = self.get_host_info(host) + if not kwargs: + kwargs = {} + kwargs['timeout'] = self.timeout + if _ver_info == (2, 6): + result = HTTPS(host, None, **kwargs) + else: + if not self._connection or host != self._connection[0]: + self._extra_headers = eh + self._connection = host, httplib.HTTPSConnection(h, None, + **kwargs) + result = self._connection[1] + return result class ServerProxy(xmlrpclib.ServerProxy): @@ -1595,3 +1603,9 @@ def run_command(self, cmd, **kwargs): elif self.verbose: sys.stderr.write('done.\n') return p + + +def normalize_name(name): + """Normalize a python package name a la PEP 503""" + # https://www.python.org/dev/peps/pep-0503/#normalized-names + return re.sub('[-_.]+', '-', name).lower() diff --git a/pip/_vendor/distlib/version.py b/pip/_vendor/distlib/version.py --- a/pip/_vendor/distlib/version.py +++ b/pip/_vendor/distlib/version.py @@ -137,7 +137,7 @@ def match(self, version): Check if the provided version matches the constraints. :param version: The version to match against this instance. - :type version: Strring or :class:`Version` instance. + :type version: String or :class:`Version` instance. """ if isinstance(version, string_types): version = self.version_class(version) @@ -265,7 +265,7 @@ class NormalizedVersion(Version): TODO: fill this out Bad: - 1 # mininum two numbers + 1 # minimum two numbers 1.2a # release level must have a release serial 1.2.3b """ @@ -494,7 +494,7 @@ def _suggest_normalized_version(s): rs = re.sub(r"dev$", r"dev0", rs) # if we have something like "b-2" or "a.2" at the end of the - # version, that is pobably beta, alpha, etc + # version, that is probably beta, alpha, etc # let's remove the dash or dot rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs) diff --git a/pip/_vendor/distro.py b/pip/_vendor/distro.py --- a/pip/_vendor/distro.py +++ b/pip/_vendor/distro.py @@ -31,11 +31,14 @@ import os import re import sys +import json import shlex +import logging import subprocess -from pip._vendor import six +if not sys.platform.startswith('linux'): + raise ImportError('Unsupported platform: {0}'.format(sys.platform)) _UNIXCONFDIR = '/etc' _OS_RELEASE_BASENAME = 'os-release' @@ -47,8 +50,7 @@ #: with blanks translated to underscores. #: #: * Value: Normalized value. -NORMALIZED_OS_ID = { -} +NORMALIZED_OS_ID = {} #: Translation table for normalizing the "Distributor ID" attribute returned by #: the lsb_release command, for use by the :func:`distro.id` method. @@ -73,21 +75,22 @@ 'redhat': 'rhel', # RHEL 6.x, 7.x } - # Pattern for content of distro release file (reversed) _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile( r'(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)') # Pattern for base file name of distro release file _DISTRO_RELEASE_BASENAME_PATTERN = re.compile( - r'(\w+)[-_](release|version)') + r'(\w+)[-_](release|version)$') # Base file names to be ignored when searching for distro release file -_DISTRO_RELEASE_IGNORE_BASENAMES = [ +_DISTRO_RELEASE_IGNORE_BASENAMES = ( 'debian_version', - 'system-release', - _OS_RELEASE_BASENAME -] + 'lsb-release', + 'oem-release', + _OS_RELEASE_BASENAME, + 'system-release' +) def linux_distribution(full_distribution_name=True): @@ -115,7 +118,7 @@ def linux_distribution(full_distribution_name=True): method normalizes the distro ID string to a reliable machine-readable value for a number of popular Linux distributions. """ - return _distroi.linux_distribution(full_distribution_name) + return _distro.linux_distribution(full_distribution_name) def id(): @@ -190,7 +193,7 @@ def id(): command, with ID values that differ from what was previously determined from the distro release file name. """ - return _distroi.id() + return _distro.id() def name(pretty=False): @@ -229,7 +232,7 @@ def name(pretty=False): with the value of the pretty version ("<version_id>" and "<codename>" fields) of the distro release file, if available. """ - return _distroi.name(pretty) + return _distro.name(pretty) def version(pretty=False, best=False): @@ -273,7 +276,7 @@ def version(pretty=False, best=False): the lsb_release command, if it follows the format of the distro release files. """ - return _distroi.version(pretty, best) + return _distro.version(pretty, best) def version_parts(best=False): @@ -290,7 +293,7 @@ def version_parts(best=False): For a description of the *best* parameter, see the :func:`distro.version` method. """ - return _distroi.version_parts(best) + return _distro.version_parts(best) def major_version(best=False): @@ -303,7 +306,7 @@ def major_version(best=False): For a description of the *best* parameter, see the :func:`distro.version` method. """ - return _distroi.major_version(best) + return _distro.major_version(best) def minor_version(best=False): @@ -316,7 +319,7 @@ def minor_version(best=False): For a description of the *best* parameter, see the :func:`distro.version` method. """ - return _distroi.minor_version(best) + return _distro.minor_version(best) def build_number(best=False): @@ -329,7 +332,7 @@ def build_number(best=False): For a description of the *best* parameter, see the :func:`distro.version` method. """ - return _distroi.build_number(best) + return _distro.build_number(best) def like(): @@ -346,7 +349,7 @@ def like(): `os-release man page <http://www.freedesktop.org/software/systemd/man/os-release.html>`_. """ - return _distroi.like() + return _distro.like() def codename(): @@ -370,7 +373,7 @@ def codename(): * the value of the "<codename>" field of the distro release file. """ - return _distroi.codename() + return _distro.codename() def info(pretty=False, best=False): @@ -414,7 +417,7 @@ def info(pretty=False, best=False): For a description of the *pretty* and *best* parameters, see the :func:`distro.version` method. """ - return _distroi.info(pretty, best) + return _distro.info(pretty, best) def os_release_info(): @@ -424,7 +427,7 @@ def os_release_info(): See `os-release file`_ for details about these information items. """ - return _distroi.os_release_info() + return _distro.os_release_info() def lsb_release_info(): @@ -435,7 +438,7 @@ def lsb_release_info(): See `lsb_release command output`_ for details about these information items. """ - return _distroi.lsb_release_info() + return _distro.lsb_release_info() def distro_release_info(): @@ -445,7 +448,7 @@ def distro_release_info(): See `distro release file`_ for details about these information items. """ - return _distroi.distro_release_info() + return _distro.distro_release_info() def os_release_attr(attribute): @@ -464,7 +467,7 @@ def os_release_attr(attribute): See `os-release file`_ for details about these information items. """ - return _distroi.os_release_attr(attribute) + return _distro.os_release_attr(attribute) def lsb_release_attr(attribute): @@ -484,7 +487,7 @@ def lsb_release_attr(attribute): See `lsb_release command output`_ for details about these information items. """ - return _distroi.lsb_release_attr(attribute) + return _distro.lsb_release_attr(attribute) def distro_release_attr(attribute): @@ -503,7 +506,7 @@ def distro_release_attr(attribute): See `distro release file`_ for details about these information items. """ - return _distroi.distro_release_attr(attribute) + return _distro.distro_release_attr(attribute) class LinuxDistribution(object): @@ -625,20 +628,22 @@ def id(self): For details, see :func:`distro.id`. """ + + def normalize(distro_id, table): + distro_id = distro_id.lower().replace(' ', '_') + return table.get(distro_id, distro_id) + distro_id = self.os_release_attr('id') if distro_id: - distro_id = distro_id.lower().replace(' ', '_') - return NORMALIZED_OS_ID.get(distro_id, distro_id) + return normalize(distro_id, NORMALIZED_OS_ID) distro_id = self.lsb_release_attr('distributor_id') if distro_id: - distro_id = distro_id.lower().replace(' ', '_') - return NORMALIZED_LSB_ID.get(distro_id, distro_id) + return normalize(distro_id, NORMALIZED_LSB_ID) distro_id = self.distro_release_attr('id') if distro_id: - distro_id = distro_id.lower().replace(' ', '_') - return NORMALIZED_DISTRO_ID.get(distro_id, distro_id) + return normalize(distro_id, NORMALIZED_DISTRO_ID) return '' @@ -703,12 +708,12 @@ def version_parts(self, best=False): """ version_str = self.version(best=best) if version_str: - g = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?') - m = g.match(version_str) - if m: - major, minor, build_number = m.groups() - return (major, minor or '', build_number or '') - return ('', '', '') + version_regex = re.compile(r'(\d+)\.?(\d+)?\.?(\d+)?') + matches = version_regex.match(version_str) + if matches: + major, minor, build_number = matches.groups() + return major, minor or '', build_number or '' + return '', '', '' def major_version(self, best=False): """ @@ -836,8 +841,8 @@ def _os_release_info(self): A dictionary containing all information items. """ if os.path.isfile(self.os_release_file): - with open(self.os_release_file, 'r') as f: - return self._parse_os_release_content(f) + with open(self.os_release_file) as release_file: + return self._parse_os_release_content(release_file) return {} @staticmethod @@ -865,7 +870,7 @@ def _parse_os_release_content(lines): # string. This causes a UnicodeDecodeError to be raised when the # parsed content is a unicode object. The following fix resolves that # (... but it should be fixed in shlex...): - if sys.version_info[0] == 2 and isinstance(lexer.wordchars, str): + if sys.version_info[0] == 2 and isinstance(lexer.wordchars, bytes): lexer.wordchars = lexer.wordchars.decode('iso-8859-1') tokens = list(lexer) @@ -878,7 +883,7 @@ def _parse_os_release_content(lines): # * commands or their arguments (not allowed in os-release) if '=' in token: k, v = token.split('=', 1) - if isinstance(v, six.binary_type): + if isinstance(v, bytes): v = v.decode('utf-8') props[k.lower()] = v if k == 'VERSION': @@ -908,23 +913,26 @@ def _lsb_release_info(self): A dictionary containing all information items. """ cmd = 'lsb_release -a' - p = subprocess.Popen( + process = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - out, err = p.communicate() - rc = p.returncode - if rc == 0: - content = out.decode('ascii').splitlines() + stdout, stderr = process.communicate() + stdout, stderr = stdout.decode('ascii'), stderr.decode('ascii') + code = process.returncode + if code == 0: + content = stdout.splitlines() return self._parse_lsb_release_content(content) - elif rc == 127: # Command not found + elif code == 127: # Command not found return {} else: - if sys.version_info[0:2] >= (2, 7): - raise subprocess.CalledProcessError(rc, cmd, err) - else: - raise subprocess.CalledProcessError(rc, cmd) + if sys.version_info[:2] >= (3, 5): + raise subprocess.CalledProcessError(code, cmd, stdout, stderr) + elif sys.version_info[:2] >= (2, 7): + raise subprocess.CalledProcessError(code, cmd, stdout) + elif sys.version_info[:2] == (2, 6): + raise subprocess.CalledProcessError(code, cmd) @staticmethod def _parse_lsb_release_content(lines): @@ -942,7 +950,7 @@ def _parse_lsb_release_content(lines): """ props = {} for line in lines: - if isinstance(line, six.binary_type): + if isinstance(line, bytes): line = line.decode('utf-8') kv = line.strip('\n').split(':', 1) if len(kv) != 2: @@ -1005,7 +1013,7 @@ def _parse_distro_release_file(self, filepath): A dictionary containing all information items. """ if os.path.isfile(filepath): - with open(filepath, 'r') as fp: + with open(filepath) as fp: # Only parse the first line. For instance, on SLES there # are multiple lines. We don't want them... return self._parse_distro_release_content(fp.readline()) @@ -1023,18 +1031,52 @@ def _parse_distro_release_content(line): Returns: A dictionary containing all information items. """ - if isinstance(line, six.binary_type): + if isinstance(line, bytes): line = line.decode('utf-8') - m = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match( + matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match( line.strip()[::-1]) distro_info = {} - if m: - distro_info['name'] = m.group(3)[::-1] # regexp ensures non-None - if m.group(2): - distro_info['version_id'] = m.group(2)[::-1] - if m.group(1): - distro_info['codename'] = m.group(1)[::-1] + if matches: + # regexp ensures non-None + distro_info['name'] = matches.group(3)[::-1] + if matches.group(2): + distro_info['version_id'] = matches.group(2)[::-1] + if matches.group(1): + distro_info['codename'] = matches.group(1)[::-1] + elif line: + distro_info['name'] = line.strip() return distro_info -_distroi = LinuxDistribution() +_distro = LinuxDistribution() + + +def main(): + import argparse + + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + logger.addHandler(logging.StreamHandler(sys.stdout)) + + parser = argparse.ArgumentParser(description="Linux distro info tool") + parser.add_argument( + '--json', + '-j', + help="Output in machine readable format", + action="store_true") + args = parser.parse_args() + + if args.json: + logger.info(json.dumps(info())) + else: + logger.info('Name: {0}'.format(name(pretty=True))) + distribution_version = version(pretty=True) + if distribution_version: + logger.info('Version: {0}'.format(distribution_version)) + distribution_codename = codename() + if distribution_codename: + logger.info('Codename: {0}'.format(distribution_codename)) + + +if __name__ == '__main__': + main() diff --git a/pip/_vendor/html5lib/__init__.py b/pip/_vendor/html5lib/__init__.py --- a/pip/_vendor/html5lib/__init__.py +++ b/pip/_vendor/html5lib/__init__.py @@ -22,4 +22,4 @@ "getTreeWalker", "serialize"] # this has to be at the top level, see how setup.py parses this -__version__ = "1.0b8" +__version__ = "1.0b10" diff --git a/pip/_vendor/html5lib/ihatexml.py b/pip/_vendor/html5lib/_ihatexml.py similarity index 97% rename from pip/_vendor/html5lib/ihatexml.py rename to pip/_vendor/html5lib/_ihatexml.py --- a/pip/_vendor/html5lib/ihatexml.py +++ b/pip/_vendor/html5lib/_ihatexml.py @@ -175,9 +175,9 @@ def escapeRegexp(string): return string # output from the above -nonXmlNameBMPRegexp = re.compile('[\x00-,/:-@\\[-\\^`\\{-\xb6\xb8-\xbf\xd7\xf7\u0132-\u0133\u013f-\u0140\u0149\u017f\u01c4-\u01cc\u01f1-\u01f3\u01f6-\u01f9\u0218-\u024f\u02a9-\u02ba\u02c2-\u02cf\u02d2-\u02ff\u0346-\u035f\u0362-\u0385\u038b\u038d\u03a2\u03cf\u03d7-\u03d9\u03db\u03dd\u03df\u03e1\u03f4-\u0400\u040d\u0450\u045d\u0482\u0487-\u048f\u04c5-\u04c6\u04c9-\u04ca\u04cd-\u04cf\u04ec-\u04ed\u04f6-\u04f7\u04fa-\u0530\u0557-\u0558\u055a-\u0560\u0587-\u0590\u05a2\u05ba\u05be\u05c0\u05c3\u05c5-\u05cf\u05eb-\u05ef\u05f3-\u0620\u063b-\u063f\u0653-\u065f\u066a-\u066f\u06b8-\u06b9\u06bf\u06cf\u06d4\u06e9\u06ee-\u06ef\u06fa-\u0900\u0904\u093a-\u093b\u094e-\u0950\u0955-\u0957\u0964-\u0965\u0970-\u0980\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09bb\u09bd\u09c5-\u09c6\u09c9-\u09ca\u09ce-\u09d6\u09d8-\u09db\u09de\u09e4-\u09e5\u09f2-\u0a01\u0a03-\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a3b\u0a3d\u0a43-\u0a46\u0a49-\u0a4a\u0a4e-\u0a58\u0a5d\u0a5f-\u0a65\u0a75-\u0a80\u0a84\u0a8c\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abb\u0ac6\u0aca\u0ace-\u0adf\u0ae1-\u0ae5\u0af0-\u0b00\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34-\u0b35\u0b3a-\u0b3b\u0b44-\u0b46\u0b49-\u0b4a\u0b4e-\u0b55\u0b58-\u0b5b\u0b5e\u0b62-\u0b65\u0b70-\u0b81\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bb6\u0bba-\u0bbd\u0bc3-\u0bc5\u0bc9\u0bce-\u0bd6\u0bd8-\u0be6\u0bf0-\u0c00\u0c04\u0c0d\u0c11\u0c29\u0c34\u0c3a-\u0c3d\u0c45\u0c49\u0c4e-\u0c54\u0c57-\u0c5f\u0c62-\u0c65\u0c70-\u0c81\u0c84\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cbd\u0cc5\u0cc9\u0cce-\u0cd4\u0cd7-\u0cdd\u0cdf\u0ce2-\u0ce5\u0cf0-\u0d01\u0d04\u0d0d\u0d11\u0d29\u0d3a-\u0d3d\u0d44-\u0d45\u0d49\u0d4e-\u0d56\u0d58-\u0d5f\u0d62-\u0d65\u0d70-\u0e00\u0e2f\u0e3b-\u0e3f\u0e4f\u0e5a-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eaf\u0eba\u0ebe-\u0ebf\u0ec5\u0ec7\u0ece-\u0ecf\u0eda-\u0f17\u0f1a-\u0f1f\u0f2a-\u0f34\u0f36\u0f38\u0f3a-\u0f3d\u0f48\u0f6a-\u0f70\u0f85\u0f8c-\u0f8f\u0f96\u0f98\u0fae-\u0fb0\u0fb8\u0fba-\u109f\u10c6-\u10cf\u10f7-\u10ff\u1101\u1104\u1108\u110a\u110d\u1113-\u113b\u113d\u113f\u1141-\u114b\u114d\u114f\u1151-\u1153\u1156-\u1158\u115a-\u115e\u1162\u1164\u1166\u1168\u116a-\u116c\u116f-\u1171\u1174\u1176-\u119d\u119f-\u11a7\u11a9-\u11aa\u11ac-\u11ad\u11b0-\u11b6\u11b9\u11bb\u11c3-\u11ea\u11ec-\u11ef\u11f1-\u11f8\u11fa-\u1dff\u1e9c-\u1e9f\u1efa-\u1eff\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fbd\u1fbf-\u1fc1\u1fc5\u1fcd-\u1fcf\u1fd4-\u1fd5\u1fdc-\u1fdf\u1fed-\u1ff1\u1ff5\u1ffd-\u20cf\u20dd-\u20e0\u20e2-\u2125\u2127-\u2129\u212c-\u212d\u212f-\u217f\u2183-\u3004\u3006\u3008-\u3020\u3030\u3036-\u3040\u3095-\u3098\u309b-\u309c\u309f-\u30a0\u30fb\u30ff-\u3104\u312d-\u4dff\u9fa6-\uabff\ud7a4-\uffff]') +nonXmlNameBMPRegexp = re.compile('[\x00-,/:-@\\[-\\^`\\{-\xb6\xb8-\xbf\xd7\xf7\u0132-\u0133\u013f-\u0140\u0149\u017f\u01c4-\u01cc\u01f1-\u01f3\u01f6-\u01f9\u0218-\u024f\u02a9-\u02ba\u02c2-\u02cf\u02d2-\u02ff\u0346-\u035f\u0362-\u0385\u038b\u038d\u03a2\u03cf\u03d7-\u03d9\u03db\u03dd\u03df\u03e1\u03f4-\u0400\u040d\u0450\u045d\u0482\u0487-\u048f\u04c5-\u04c6\u04c9-\u04ca\u04cd-\u04cf\u04ec-\u04ed\u04f6-\u04f7\u04fa-\u0530\u0557-\u0558\u055a-\u0560\u0587-\u0590\u05a2\u05ba\u05be\u05c0\u05c3\u05c5-\u05cf\u05eb-\u05ef\u05f3-\u0620\u063b-\u063f\u0653-\u065f\u066a-\u066f\u06b8-\u06b9\u06bf\u06cf\u06d4\u06e9\u06ee-\u06ef\u06fa-\u0900\u0904\u093a-\u093b\u094e-\u0950\u0955-\u0957\u0964-\u0965\u0970-\u0980\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09bb\u09bd\u09c5-\u09c6\u09c9-\u09ca\u09ce-\u09d6\u09d8-\u09db\u09de\u09e4-\u09e5\u09f2-\u0a01\u0a03-\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a3b\u0a3d\u0a43-\u0a46\u0a49-\u0a4a\u0a4e-\u0a58\u0a5d\u0a5f-\u0a65\u0a75-\u0a80\u0a84\u0a8c\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abb\u0ac6\u0aca\u0ace-\u0adf\u0ae1-\u0ae5\u0af0-\u0b00\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34-\u0b35\u0b3a-\u0b3b\u0b44-\u0b46\u0b49-\u0b4a\u0b4e-\u0b55\u0b58-\u0b5b\u0b5e\u0b62-\u0b65\u0b70-\u0b81\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bb6\u0bba-\u0bbd\u0bc3-\u0bc5\u0bc9\u0bce-\u0bd6\u0bd8-\u0be6\u0bf0-\u0c00\u0c04\u0c0d\u0c11\u0c29\u0c34\u0c3a-\u0c3d\u0c45\u0c49\u0c4e-\u0c54\u0c57-\u0c5f\u0c62-\u0c65\u0c70-\u0c81\u0c84\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cbd\u0cc5\u0cc9\u0cce-\u0cd4\u0cd7-\u0cdd\u0cdf\u0ce2-\u0ce5\u0cf0-\u0d01\u0d04\u0d0d\u0d11\u0d29\u0d3a-\u0d3d\u0d44-\u0d45\u0d49\u0d4e-\u0d56\u0d58-\u0d5f\u0d62-\u0d65\u0d70-\u0e00\u0e2f\u0e3b-\u0e3f\u0e4f\u0e5a-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eaf\u0eba\u0ebe-\u0ebf\u0ec5\u0ec7\u0ece-\u0ecf\u0eda-\u0f17\u0f1a-\u0f1f\u0f2a-\u0f34\u0f36\u0f38\u0f3a-\u0f3d\u0f48\u0f6a-\u0f70\u0f85\u0f8c-\u0f8f\u0f96\u0f98\u0fae-\u0fb0\u0fb8\u0fba-\u109f\u10c6-\u10cf\u10f7-\u10ff\u1101\u1104\u1108\u110a\u110d\u1113-\u113b\u113d\u113f\u1141-\u114b\u114d\u114f\u1151-\u1153\u1156-\u1158\u115a-\u115e\u1162\u1164\u1166\u1168\u116a-\u116c\u116f-\u1171\u1174\u1176-\u119d\u119f-\u11a7\u11a9-\u11aa\u11ac-\u11ad\u11b0-\u11b6\u11b9\u11bb\u11c3-\u11ea\u11ec-\u11ef\u11f1-\u11f8\u11fa-\u1dff\u1e9c-\u1e9f\u1efa-\u1eff\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fbd\u1fbf-\u1fc1\u1fc5\u1fcd-\u1fcf\u1fd4-\u1fd5\u1fdc-\u1fdf\u1fed-\u1ff1\u1ff5\u1ffd-\u20cf\u20dd-\u20e0\u20e2-\u2125\u2127-\u2129\u212c-\u212d\u212f-\u217f\u2183-\u3004\u3006\u3008-\u3020\u3030\u3036-\u3040\u3095-\u3098\u309b-\u309c\u309f-\u30a0\u30fb\u30ff-\u3104\u312d-\u4dff\u9fa6-\uabff\ud7a4-\uffff]') # noqa -nonXmlNameFirstBMPRegexp = re.compile('[\x00-@\\[-\\^`\\{-\xbf\xd7\xf7\u0132-\u0133\u013f-\u0140\u0149\u017f\u01c4-\u01cc\u01f1-\u01f3\u01f6-\u01f9\u0218-\u024f\u02a9-\u02ba\u02c2-\u0385\u0387\u038b\u038d\u03a2\u03cf\u03d7-\u03d9\u03db\u03dd\u03df\u03e1\u03f4-\u0400\u040d\u0450\u045d\u0482-\u048f\u04c5-\u04c6\u04c9-\u04ca\u04cd-\u04cf\u04ec-\u04ed\u04f6-\u04f7\u04fa-\u0530\u0557-\u0558\u055a-\u0560\u0587-\u05cf\u05eb-\u05ef\u05f3-\u0620\u063b-\u0640\u064b-\u0670\u06b8-\u06b9\u06bf\u06cf\u06d4\u06d6-\u06e4\u06e7-\u0904\u093a-\u093c\u093e-\u0957\u0962-\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09db\u09de\u09e2-\u09ef\u09f2-\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a58\u0a5d\u0a5f-\u0a71\u0a75-\u0a84\u0a8c\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abc\u0abe-\u0adf\u0ae1-\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34-\u0b35\u0b3a-\u0b3c\u0b3e-\u0b5b\u0b5e\u0b62-\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bb6\u0bba-\u0c04\u0c0d\u0c11\u0c29\u0c34\u0c3a-\u0c5f\u0c62-\u0c84\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cdd\u0cdf\u0ce2-\u0d04\u0d0d\u0d11\u0d29\u0d3a-\u0d5f\u0d62-\u0e00\u0e2f\u0e31\u0e34-\u0e3f\u0e46-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eaf\u0eb1\u0eb4-\u0ebc\u0ebe-\u0ebf\u0ec5-\u0f3f\u0f48\u0f6a-\u109f\u10c6-\u10cf\u10f7-\u10ff\u1101\u1104\u1108\u110a\u110d\u1113-\u113b\u113d\u113f\u1141-\u114b\u114d\u114f\u1151-\u1153\u1156-\u1158\u115a-\u115e\u1162\u1164\u1166\u1168\u116a-\u116c\u116f-\u1171\u1174\u1176-\u119d\u119f-\u11a7\u11a9-\u11aa\u11ac-\u11ad\u11b0-\u11b6\u11b9\u11bb\u11c3-\u11ea\u11ec-\u11ef\u11f1-\u11f8\u11fa-\u1dff\u1e9c-\u1e9f\u1efa-\u1eff\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fbd\u1fbf-\u1fc1\u1fc5\u1fcd-\u1fcf\u1fd4-\u1fd5\u1fdc-\u1fdf\u1fed-\u1ff1\u1ff5\u1ffd-\u2125\u2127-\u2129\u212c-\u212d\u212f-\u217f\u2183-\u3006\u3008-\u3020\u302a-\u3040\u3095-\u30a0\u30fb-\u3104\u312d-\u4dff\u9fa6-\uabff\ud7a4-\uffff]') +nonXmlNameFirstBMPRegexp = re.compile('[\x00-@\\[-\\^`\\{-\xbf\xd7\xf7\u0132-\u0133\u013f-\u0140\u0149\u017f\u01c4-\u01cc\u01f1-\u01f3\u01f6-\u01f9\u0218-\u024f\u02a9-\u02ba\u02c2-\u0385\u0387\u038b\u038d\u03a2\u03cf\u03d7-\u03d9\u03db\u03dd\u03df\u03e1\u03f4-\u0400\u040d\u0450\u045d\u0482-\u048f\u04c5-\u04c6\u04c9-\u04ca\u04cd-\u04cf\u04ec-\u04ed\u04f6-\u04f7\u04fa-\u0530\u0557-\u0558\u055a-\u0560\u0587-\u05cf\u05eb-\u05ef\u05f3-\u0620\u063b-\u0640\u064b-\u0670\u06b8-\u06b9\u06bf\u06cf\u06d4\u06d6-\u06e4\u06e7-\u0904\u093a-\u093c\u093e-\u0957\u0962-\u0984\u098d-\u098e\u0991-\u0992\u09a9\u09b1\u09b3-\u09b5\u09ba-\u09db\u09de\u09e2-\u09ef\u09f2-\u0a04\u0a0b-\u0a0e\u0a11-\u0a12\u0a29\u0a31\u0a34\u0a37\u0a3a-\u0a58\u0a5d\u0a5f-\u0a71\u0a75-\u0a84\u0a8c\u0a8e\u0a92\u0aa9\u0ab1\u0ab4\u0aba-\u0abc\u0abe-\u0adf\u0ae1-\u0b04\u0b0d-\u0b0e\u0b11-\u0b12\u0b29\u0b31\u0b34-\u0b35\u0b3a-\u0b3c\u0b3e-\u0b5b\u0b5e\u0b62-\u0b84\u0b8b-\u0b8d\u0b91\u0b96-\u0b98\u0b9b\u0b9d\u0ba0-\u0ba2\u0ba5-\u0ba7\u0bab-\u0bad\u0bb6\u0bba-\u0c04\u0c0d\u0c11\u0c29\u0c34\u0c3a-\u0c5f\u0c62-\u0c84\u0c8d\u0c91\u0ca9\u0cb4\u0cba-\u0cdd\u0cdf\u0ce2-\u0d04\u0d0d\u0d11\u0d29\u0d3a-\u0d5f\u0d62-\u0e00\u0e2f\u0e31\u0e34-\u0e3f\u0e46-\u0e80\u0e83\u0e85-\u0e86\u0e89\u0e8b-\u0e8c\u0e8e-\u0e93\u0e98\u0ea0\u0ea4\u0ea6\u0ea8-\u0ea9\u0eac\u0eaf\u0eb1\u0eb4-\u0ebc\u0ebe-\u0ebf\u0ec5-\u0f3f\u0f48\u0f6a-\u109f\u10c6-\u10cf\u10f7-\u10ff\u1101\u1104\u1108\u110a\u110d\u1113-\u113b\u113d\u113f\u1141-\u114b\u114d\u114f\u1151-\u1153\u1156-\u1158\u115a-\u115e\u1162\u1164\u1166\u1168\u116a-\u116c\u116f-\u1171\u1174\u1176-\u119d\u119f-\u11a7\u11a9-\u11aa\u11ac-\u11ad\u11b0-\u11b6\u11b9\u11bb\u11c3-\u11ea\u11ec-\u11ef\u11f1-\u11f8\u11fa-\u1dff\u1e9c-\u1e9f\u1efa-\u1eff\u1f16-\u1f17\u1f1e-\u1f1f\u1f46-\u1f47\u1f4e-\u1f4f\u1f58\u1f5a\u1f5c\u1f5e\u1f7e-\u1f7f\u1fb5\u1fbd\u1fbf-\u1fc1\u1fc5\u1fcd-\u1fcf\u1fd4-\u1fd5\u1fdc-\u1fdf\u1fed-\u1ff1\u1ff5\u1ffd-\u2125\u2127-\u2129\u212c-\u212d\u212f-\u217f\u2183-\u3006\u3008-\u3020\u302a-\u3040\u3095-\u30a0\u30fb-\u3104\u312d-\u4dff\u9fa6-\uabff\ud7a4-\uffff]') # noqa # Simpler things nonPubidCharRegexp = re.compile("[^\x20\x0D\x0Aa-zA-Z0-9\-\'()+,./:=?;!*#@$_%]") @@ -186,7 +186,7 @@ def escapeRegexp(string): class InfosetFilter(object): replacementRegexp = re.compile(r"U[\dA-F]{5,5}") - def __init__(self, replaceChars=None, + def __init__(self, dropXmlnsLocalName=False, dropXmlnsAttrNs=False, preventDoubleDashComments=False, @@ -217,7 +217,7 @@ def coerceAttribute(self, name, namespace=None): else: return self.toXmlName(name) - def coerceElement(self, name, namespace=None): + def coerceElement(self, name): return self.toXmlName(name) def coerceComment(self, data): @@ -225,11 +225,14 @@ def coerceComment(self, data): while "--" in data: warnings.warn("Comments cannot contain adjacent dashes", DataLossWarning) data = data.replace("--", "- -") + if data.endswith("-"): + warnings.warn("Comments cannot end in a dash", DataLossWarning) + data += " " return data def coerceCharacters(self, data): if self.replaceFormFeedCharacters: - for i in range(data.count("\x0C")): + for _ in range(data.count("\x0C")): warnings.warn("Text cannot contain U+000C", DataLossWarning) data = data.replace("\x0C", " ") # Other non-xml characters diff --git a/pip/_vendor/html5lib/inputstream.py b/pip/_vendor/html5lib/_inputstream.py similarity index 83% rename from pip/_vendor/html5lib/inputstream.py rename to pip/_vendor/html5lib/_inputstream.py --- a/pip/_vendor/html5lib/inputstream.py +++ b/pip/_vendor/html5lib/_inputstream.py @@ -1,13 +1,16 @@ from __future__ import absolute_import, division, unicode_literals -from pip._vendor.six import text_type -from pip._vendor.six.moves import http_client + +from pip._vendor.six import text_type, binary_type +from pip._vendor.six.moves import http_client, urllib import codecs import re +from pip._vendor import webencodings + from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase -from .constants import encodings, ReparseException -from . import utils +from .constants import ReparseException +from . import _utils from io import StringIO @@ -16,12 +19,6 @@ except ImportError: BytesIO = StringIO -try: - from io import BufferedIOBase -except ImportError: - class BufferedIOBase(object): - pass - # Non-unicode versions of constants for use in the pre-parser spaceCharactersBytes = frozenset([item.encode("ascii") for item in spaceCharacters]) asciiLettersBytes = frozenset([item.encode("ascii") for item in asciiLetters]) @@ -29,15 +26,17 @@ class BufferedIOBase(object): spacesAngleBrackets = spaceCharactersBytes | frozenset([b">", b"<"]) -invalid_unicode_no_surrogate = "[\u0001-\u0008\u000B\u000E-\u001F\u007F-\u009F\uFDD0-\uFDEF\uFFFE\uFFFF\U0001FFFE\U0001FFFF\U0002FFFE\U0002FFFF\U0003FFFE\U0003FFFF\U0004FFFE\U0004FFFF\U0005FFFE\U0005FFFF\U0006FFFE\U0006FFFF\U0007FFFE\U0007FFFF\U0008FFFE\U0008FFFF\U0009FFFE\U0009FFFF\U000AFFFE\U000AFFFF\U000BFFFE\U000BFFFF\U000CFFFE\U000CFFFF\U000DFFFE\U000DFFFF\U000EFFFE\U000EFFFF\U000FFFFE\U000FFFFF\U0010FFFE\U0010FFFF]" +invalid_unicode_no_surrogate = "[\u0001-\u0008\u000B\u000E-\u001F\u007F-\u009F\uFDD0-\uFDEF\uFFFE\uFFFF\U0001FFFE\U0001FFFF\U0002FFFE\U0002FFFF\U0003FFFE\U0003FFFF\U0004FFFE\U0004FFFF\U0005FFFE\U0005FFFF\U0006FFFE\U0006FFFF\U0007FFFE\U0007FFFF\U0008FFFE\U0008FFFF\U0009FFFE\U0009FFFF\U000AFFFE\U000AFFFF\U000BFFFE\U000BFFFF\U000CFFFE\U000CFFFF\U000DFFFE\U000DFFFF\U000EFFFE\U000EFFFF\U000FFFFE\U000FFFFF\U0010FFFE\U0010FFFF]" # noqa -if utils.supports_lone_surrogates: +if _utils.supports_lone_surrogates: # Use one extra step of indirection and create surrogates with - # unichr. Not using this indirection would introduce an illegal + # eval. Not using this indirection would introduce an illegal # unicode literal on platforms not supporting such lone # surrogates. - invalid_unicode_re = re.compile(invalid_unicode_no_surrogate + - eval('"\\uD800-\\uDFFF"')) + assert invalid_unicode_no_surrogate[-1] == "]" and invalid_unicode_no_surrogate.count("]") == 1 + invalid_unicode_re = re.compile(invalid_unicode_no_surrogate[:-1] + + eval('"\\uD800-\\uDFFF"') + # pylint:disable=eval-used + "]") else: invalid_unicode_re = re.compile(invalid_unicode_no_surrogate) @@ -129,10 +128,13 @@ def _readFromBuffer(self, bytes): return b"".join(rv) -def HTMLInputStream(source, encoding=None, parseMeta=True, chardet=True): - if isinstance(source, http_client.HTTPResponse): - # Work around Python bug #20007: read(0) closes the connection. - # http://bugs.python.org/issue20007 +def HTMLInputStream(source, **kwargs): + # Work around Python bug #20007: read(0) closes the connection. + # http://bugs.python.org/issue20007 + if (isinstance(source, http_client.HTTPResponse) or + # Also check for addinfourl wrapping HTTPResponse + (isinstance(source, urllib.response.addbase) and + isinstance(source.fp, http_client.HTTPResponse))): isUnicode = False elif hasattr(source, "read"): isUnicode = isinstance(source.read(0), text_type) @@ -140,12 +142,13 @@ def HTMLInputStream(source, encoding=None, parseMeta=True, chardet=True): isUnicode = isinstance(source, text_type) if isUnicode: - if encoding is not None: - raise TypeError("Cannot explicitly set an encoding with a unicode string") + encodings = [x for x in kwargs if x.endswith("_encoding")] + if encodings: + raise TypeError("Cannot set an encoding with a unicode input, set %r" % encodings) - return HTMLUnicodeInputStream(source) + return HTMLUnicodeInputStream(source, **kwargs) else: - return HTMLBinaryInputStream(source, encoding, parseMeta, chardet) + return HTMLBinaryInputStream(source, **kwargs) class HTMLUnicodeInputStream(object): @@ -171,27 +174,21 @@ def __init__(self, source): regardless of any BOM or later declaration (such as in a meta element) - parseMeta - Look for a <meta> element containing encoding information - """ - if not utils.supports_lone_surrogates: + if not _utils.supports_lone_surrogates: # Such platforms will have already checked for such # surrogate errors, so no need to do this checking. self.reportCharacterErrors = None - self.replaceCharactersRegexp = None elif len("\U0010FFFF") == 1: self.reportCharacterErrors = self.characterErrorsUCS4 - self.replaceCharactersRegexp = re.compile(eval('"[\\uD800-\\uDFFF]"')) else: self.reportCharacterErrors = self.characterErrorsUCS2 - self.replaceCharactersRegexp = re.compile( - eval('"([\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF])"')) # List of where new lines occur self.newLines = [0] - self.charEncoding = ("utf-8", "certain") + self.charEncoding = (lookupEncoding("utf-8"), "certain") self.dataStream = self.openStream(source) self.reset() @@ -284,10 +281,7 @@ def readChunk(self, chunkSize=None): if self.reportCharacterErrors: self.reportCharacterErrors(data) - # Replace invalid characters - # Note U+0000 is dealt with in the tokenizer - data = self.replaceCharactersRegexp.sub("\ufffd", data) - + # Replace invalid characters data = data.replace("\r\n", "\n") data = data.replace("\r", "\n") @@ -297,7 +291,7 @@ def readChunk(self, chunkSize=None): return True def characterErrorsUCS4(self, data): - for i in range(len(invalid_unicode_re.findall(data))): + for _ in range(len(invalid_unicode_re.findall(data))): self.errors.append("invalid-codepoint") def characterErrorsUCS2(self, data): @@ -310,9 +304,9 @@ def characterErrorsUCS2(self, data): codepoint = ord(match.group()) pos = match.start() # Pretty sure there should be endianness issues here - if utils.isSurrogatePair(data[pos:pos + 2]): + if _utils.isSurrogatePair(data[pos:pos + 2]): # We have a surrogate pair! - char_val = utils.surrogatePairToCodepoint(data[pos:pos + 2]) + char_val = _utils.surrogatePairToCodepoint(data[pos:pos + 2]) if char_val in non_bmp_invalid_codepoints: self.errors.append("invalid-codepoint") skip = True @@ -395,7 +389,9 @@ class HTMLBinaryInputStream(HTMLUnicodeInputStream): """ - def __init__(self, source, encoding=None, parseMeta=True, chardet=True): + def __init__(self, source, override_encoding=None, transport_encoding=None, + same_origin_parent_encoding=None, likely_encoding=None, + default_encoding="windows-1252", useChardet=True): """Initialises the HTMLInputStream. HTMLInputStream(source, [encoding]) -> Normalized stream from source @@ -408,8 +404,6 @@ def __init__(self, source, encoding=None, parseMeta=True, chardet=True): regardless of any BOM or later declaration (such as in a meta element) - parseMeta - Look for a <meta> element containing encoding information - """ # Raw Stream - for unicode objects this will encode to utf-8 and set # self.charEncoding as appropriate @@ -417,27 +411,28 @@ def __init__(self, source, encoding=None, parseMeta=True, chardet=True): HTMLUnicodeInputStream.__init__(self, self.rawStream) - self.charEncoding = (codecName(encoding), "certain") - # Encoding Information # Number of bytes to use when looking for a meta element with # encoding information - self.numBytesMeta = 512 + self.numBytesMeta = 1024 # Number of bytes to use when using detecting encoding using chardet self.numBytesChardet = 100 - # Encoding to use if no other information can be found - self.defaultEncoding = "windows-1252" + # Things from args + self.override_encoding = override_encoding + self.transport_encoding = transport_encoding + self.same_origin_parent_encoding = same_origin_parent_encoding + self.likely_encoding = likely_encoding + self.default_encoding = default_encoding - # Detect encoding iff no explicit "transport level" encoding is supplied - if (self.charEncoding[0] is None): - self.charEncoding = self.detectEncoding(parseMeta, chardet) + # Determine encoding + self.charEncoding = self.determineEncoding(useChardet) + assert self.charEncoding[0] is not None # Call superclass self.reset() def reset(self): - self.dataStream = codecs.getreader(self.charEncoding[0])(self.rawStream, - 'replace') + self.dataStream = self.charEncoding[0].codec_info.streamreader(self.rawStream, 'replace') HTMLUnicodeInputStream.reset(self) def openStream(self, source): @@ -454,29 +449,50 @@ def openStream(self, source): try: stream.seek(stream.tell()) - except: + except: # pylint:disable=bare-except stream = BufferedStream(stream) return stream - def detectEncoding(self, parseMeta=True, chardet=True): - # First look for a BOM + def determineEncoding(self, chardet=True): + # BOMs take precedence over everything # This will also read past the BOM if present - encoding = self.detectBOM() - confidence = "certain" - # If there is no BOM need to look for meta elements with encoding - # information - if encoding is None and parseMeta: - encoding = self.detectEncodingMeta() - confidence = "tentative" - # Guess with chardet, if avaliable - if encoding is None and chardet: - confidence = "tentative" + charEncoding = self.detectBOM(), "certain" + if charEncoding[0] is not None: + return charEncoding + + # If we've been overriden, we've been overriden + charEncoding = lookupEncoding(self.override_encoding), "certain" + if charEncoding[0] is not None: + return charEncoding + + # Now check the transport layer + charEncoding = lookupEncoding(self.transport_encoding), "certain" + if charEncoding[0] is not None: + return charEncoding + + # Look for meta elements with encoding information + charEncoding = self.detectEncodingMeta(), "tentative" + if charEncoding[0] is not None: + return charEncoding + + # Parent document encoding + charEncoding = lookupEncoding(self.same_origin_parent_encoding), "tentative" + if charEncoding[0] is not None and not charEncoding[0].name.startswith("utf-16"): + return charEncoding + + # "likely" encoding + charEncoding = lookupEncoding(self.likely_encoding), "tentative" + if charEncoding[0] is not None: + return charEncoding + + # Guess with chardet, if available + if chardet: try: - try: - from charade.universaldetector import UniversalDetector - except ImportError: - from chardet.universaldetector import UniversalDetector + from chardet.universaldetector import UniversalDetector + except ImportError: + pass + else: buffers = [] detector = UniversalDetector() while not detector.done: @@ -487,36 +503,33 @@ def detectEncoding(self, parseMeta=True, chardet=True): buffers.append(buffer) detector.feed(buffer) detector.close() - encoding = detector.result['encoding'] + encoding = lookupEncoding(detector.result['encoding']) self.rawStream.seek(0) - except ImportError: - pass - # If all else fails use the default encoding - if encoding is None: - confidence = "tentative" - encoding = self.defaultEncoding + if encoding is not None: + return encoding, "tentative" - # Substitute for equivalent encodings: - encodingSub = {"iso-8859-1": "windows-1252"} + # Try the default encoding + charEncoding = lookupEncoding(self.default_encoding), "tentative" + if charEncoding[0] is not None: + return charEncoding - if encoding.lower() in encodingSub: - encoding = encodingSub[encoding.lower()] - - return encoding, confidence + # Fallback to html5lib's default if even that hasn't worked + return lookupEncoding("windows-1252"), "tentative" def changeEncoding(self, newEncoding): assert self.charEncoding[1] != "certain" - newEncoding = codecName(newEncoding) - if newEncoding in ("utf-16", "utf-16-be", "utf-16-le"): - newEncoding = "utf-8" + newEncoding = lookupEncoding(newEncoding) if newEncoding is None: return + if newEncoding.name in ("utf-16be", "utf-16le"): + newEncoding = lookupEncoding("utf-8") + assert newEncoding is not None elif newEncoding == self.charEncoding[0]: self.charEncoding = (self.charEncoding[0], "certain") else: self.rawStream.seek(0) - self.reset() self.charEncoding = (newEncoding, "certain") + self.reset() raise ReparseException("Encoding changed from %s to %s" % (self.charEncoding[0], newEncoding)) def detectBOM(self): @@ -525,8 +538,8 @@ def detectBOM(self): encoding otherwise return None""" bomDict = { codecs.BOM_UTF8: 'utf-8', - codecs.BOM_UTF16_LE: 'utf-16-le', codecs.BOM_UTF16_BE: 'utf-16-be', - codecs.BOM_UTF32_LE: 'utf-32-le', codecs.BOM_UTF32_BE: 'utf-32-be' + codecs.BOM_UTF16_LE: 'utf-16le', codecs.BOM_UTF16_BE: 'utf-16be', + codecs.BOM_UTF32_LE: 'utf-32le', codecs.BOM_UTF32_BE: 'utf-32be' } # Go to beginning of file and read in 4 bytes @@ -546,9 +559,12 @@ def detectBOM(self): # Set the read position past the BOM if one was found, otherwise # set it to the start of the stream - self.rawStream.seek(encoding and seek or 0) - - return encoding + if encoding: + self.rawStream.seek(seek) + return lookupEncoding(encoding) + else: + self.rawStream.seek(0) + return None def detectEncodingMeta(self): """Report the encoding declared by the meta element @@ -559,8 +575,8 @@ def detectEncodingMeta(self): self.rawStream.seek(0) encoding = parser.getEncoding() - if encoding in ("utf-16", "utf-16-be", "utf-16-le"): - encoding = "utf-8" + if encoding is not None and encoding.name in ("utf-16be", "utf-16le"): + encoding = lookupEncoding("utf-8") return encoding @@ -574,6 +590,7 @@ def __new__(self, value): return bytes.__new__(self, value.lower()) def __init__(self, value): + # pylint:disable=unused-argument self._position = -1 def __iter__(self): @@ -684,7 +701,7 @@ def getEncoding(self): (b"<!", self.handleOther), (b"<?", self.handleOther), (b"<", self.handlePossibleStartTag)) - for byte in self.data: + for _ in self.data: keepParsing = True for key, method in methodDispatch: if self.data.matchBytes(key): @@ -723,7 +740,7 @@ def handleMeta(self): return False elif attr[0] == b"charset": tentativeEncoding = attr[1] - codec = codecName(tentativeEncoding) + codec = lookupEncoding(tentativeEncoding) if codec is not None: self.encoding = codec return False @@ -731,7 +748,7 @@ def handleMeta(self): contentParser = ContentAttrParser(EncodingBytes(attr[1])) tentativeEncoding = contentParser.parse() if tentativeEncoding is not None: - codec = codecName(tentativeEncoding) + codec = lookupEncoding(tentativeEncoding) if codec is not None: if hasPragma: self.encoding = codec @@ -888,16 +905,19 @@ def parse(self): return None -def codecName(encoding): +def lookupEncoding(encoding): """Return the python codec name corresponding to an encoding or None if the string doesn't correspond to a valid encoding.""" - if isinstance(encoding, bytes): + if isinstance(encoding, binary_type): try: encoding = encoding.decode("ascii") except UnicodeDecodeError: return None - if encoding: - canonicalName = ascii_punctuation_re.sub("", encoding).lower() - return encodings.get(canonicalName, None) + + if encoding is not None: + try: + return webencodings.lookup(encoding) + except AttributeError: + return None else: return None diff --git a/pip/_vendor/html5lib/tokenizer.py b/pip/_vendor/html5lib/_tokenizer.py similarity index 98% rename from pip/_vendor/html5lib/tokenizer.py rename to pip/_vendor/html5lib/_tokenizer.py --- a/pip/_vendor/html5lib/tokenizer.py +++ b/pip/_vendor/html5lib/_tokenizer.py @@ -1,9 +1,6 @@ from __future__ import absolute_import, division, unicode_literals -try: - chr = unichr # flake8: noqa -except NameError: - pass +from pip._vendor.six import unichr as chr from collections import deque @@ -14,9 +11,9 @@ from .constants import tokenTypes, tagTokenTypes from .constants import replacementCharacters -from .inputstream import HTMLInputStream +from ._inputstream import HTMLInputStream -from .trie import Trie +from ._trie import Trie entitiesTrie = Trie(entities) @@ -34,16 +31,11 @@ class HTMLTokenizer(object): Points to HTMLInputStream object. """ - def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True, - lowercaseElementName=True, lowercaseAttrName=True, parser=None): + def __init__(self, stream, parser=None, **kwargs): - self.stream = HTMLInputStream(stream, encoding, parseMeta, useChardet) + self.stream = HTMLInputStream(stream, **kwargs) self.parser = parser - # Perform case conversions? - self.lowercaseElementName = lowercaseElementName - self.lowercaseAttrName = lowercaseAttrName - # Setup the initial tokenizer state self.escapeFlag = False self.lastFourChars = [] @@ -147,8 +139,8 @@ def consumeEntity(self, allowedChar=None, fromAttribute=False): output = "&" charStack = [self.stream.char()] - if (charStack[0] in spaceCharacters or charStack[0] in (EOF, "<", "&") - or (allowedChar is not None and allowedChar == charStack[0])): + if (charStack[0] in spaceCharacters or charStack[0] in (EOF, "<", "&") or + (allowedChar is not None and allowedChar == charStack[0])): self.stream.unget(charStack[0]) elif charStack[0] == "#": @@ -235,8 +227,7 @@ def emitCurrentToken(self): token = self.currentToken # Add token to the queue to be yielded if (token["type"] in tagTokenTypes): - if self.lowercaseElementName: - token["name"] = token["name"].translate(asciiUpper2Lower) + token["name"] = token["name"].translate(asciiUpper2Lower) if token["type"] == tokenTypes["EndTag"]: if token["data"]: self.tokenQueue.append({"type": tokenTypes["ParseError"], @@ -921,10 +912,9 @@ def attributeNameState(self): # Attributes are not dropped at this stage. That happens when the # start tag token is emitted so values can still be safely appended # to attributes, but we do want to report the parse error in time. - if self.lowercaseAttrName: - self.currentToken["data"][-1][0] = ( - self.currentToken["data"][-1][0].translate(asciiUpper2Lower)) - for name, value in self.currentToken["data"][:-1]: + self.currentToken["data"][-1][0] = ( + self.currentToken["data"][-1][0].translate(asciiUpper2Lower)) + for name, _ in self.currentToken["data"][:-1]: if self.currentToken["data"][-1][0] == name: self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "duplicate-attribute"}) @@ -1716,11 +1706,11 @@ def cdataSectionState(self): else: data.append(char) - data = "".join(data) + data = "".join(data) # pylint:disable=redefined-variable-type # Deal with null here rather than in the parser nullCount = data.count("\u0000") if nullCount > 0: - for i in range(nullCount): + for _ in range(nullCount): self.tokenQueue.append({"type": tokenTypes["ParseError"], "data": "invalid-codepoint"}) data = data.replace("\u0000", "\uFFFD") diff --git a/pip/_vendor/html5lib/trie/__init__.py b/pip/_vendor/html5lib/_trie/__init__.py similarity index 73% rename from pip/_vendor/html5lib/trie/__init__.py rename to pip/_vendor/html5lib/_trie/__init__.py --- a/pip/_vendor/html5lib/trie/__init__.py +++ b/pip/_vendor/html5lib/_trie/__init__.py @@ -4,9 +4,11 @@ Trie = PyTrie +# pylint:disable=wrong-import-position try: from .datrie import Trie as DATrie except ImportError: pass else: Trie = DATrie +# pylint:enable=wrong-import-position diff --git a/pip/_vendor/html5lib/trie/_base.py b/pip/_vendor/html5lib/_trie/_base.py similarity index 91% rename from pip/_vendor/html5lib/trie/_base.py rename to pip/_vendor/html5lib/_trie/_base.py --- a/pip/_vendor/html5lib/trie/_base.py +++ b/pip/_vendor/html5lib/_trie/_base.py @@ -7,7 +7,8 @@ class Trie(Mapping): """Abstract base class for tries""" def keys(self, prefix=None): - keys = super().keys() + # pylint:disable=arguments-differ + keys = super(Trie, self).keys() if prefix is None: return set(keys) diff --git a/pip/_vendor/html5lib/trie/datrie.py b/pip/_vendor/html5lib/_trie/datrie.py similarity index 100% rename from pip/_vendor/html5lib/trie/datrie.py rename to pip/_vendor/html5lib/_trie/datrie.py diff --git a/pip/_vendor/html5lib/trie/py.py b/pip/_vendor/html5lib/_trie/py.py similarity index 100% rename from pip/_vendor/html5lib/trie/py.py rename to pip/_vendor/html5lib/_trie/py.py diff --git a/pip/_vendor/html5lib/utils.py b/pip/_vendor/html5lib/_utils.py similarity index 71% rename from pip/_vendor/html5lib/utils.py rename to pip/_vendor/html5lib/_utils.py --- a/pip/_vendor/html5lib/utils.py +++ b/pip/_vendor/html5lib/_utils.py @@ -1,5 +1,6 @@ from __future__ import absolute_import, division, unicode_literals +import sys from types import ModuleType from pip._vendor.six import text_type @@ -12,9 +13,11 @@ __all__ = ["default_etree", "MethodDispatcher", "isSurrogatePair", "surrogatePairToCodepoint", "moduleFactoryFactory", - "supports_lone_surrogates"] + "supports_lone_surrogates", "PY27"] +PY27 = sys.version_info[0] == 2 and sys.version_info[1] >= 7 + # Platforms not supporting lone surrogates (\uD800-\uDFFF) should be # caught by the below test. In general this would be any platform # using UTF-16 as its encoding of unicode strings, such as @@ -22,12 +25,12 @@ # surrogates, and there is no mechanism to further escape such # escapes. try: - _x = eval('"\\uD800"') + _x = eval('"\\uD800"') # pylint:disable=eval-used if not isinstance(_x, text_type): # We need this with u"" because of http://bugs.jython.org/issue2039 - _x = eval('u"\\uD800"') + _x = eval('u"\\uD800"') # pylint:disable=eval-used assert isinstance(_x, text_type) -except: +except: # pylint:disable=bare-except supports_lone_surrogates = False else: supports_lone_surrogates = True @@ -52,19 +55,20 @@ def __init__(self, items=()): # anything here. _dictEntries = [] for name, value in items: - if type(name) in (list, tuple, frozenset, set): + if isinstance(name, (list, tuple, frozenset, set)): for item in name: _dictEntries.append((item, value)) else: _dictEntries.append((name, value)) dict.__init__(self, _dictEntries) + assert len(self) == len(_dictEntries) self.default = None def __getitem__(self, key): return dict.get(self, key, self.default) -# Some utility functions to dal with weirdness around UCS2 vs UCS4 +# Some utility functions to deal with weirdness around UCS2 vs UCS4 # python builds def isSurrogatePair(data): @@ -91,13 +95,33 @@ def moduleFactory(baseModule, *args, **kwargs): else: name = b"_%s_factory" % baseModule.__name__ - if name in moduleCache: - return moduleCache[name] - else: + kwargs_tuple = tuple(kwargs.items()) + + try: + return moduleCache[name][args][kwargs_tuple] + except KeyError: mod = ModuleType(name) objs = factory(baseModule, *args, **kwargs) mod.__dict__.update(objs) - moduleCache[name] = mod + if "name" not in moduleCache: + moduleCache[name] = {} + if "args" not in moduleCache[name]: + moduleCache[name][args] = {} + if "kwargs" not in moduleCache[name][args]: + moduleCache[name][args][kwargs_tuple] = {} + moduleCache[name][args][kwargs_tuple] = mod return mod return moduleFactory + + +def memoize(func): + cache = {} + + def wrapped(*args, **kwargs): + key = (tuple(args), tuple(kwargs.items())) + if key not in cache: + cache[key] = func(*args, **kwargs) + return cache[key] + + return wrapped diff --git a/pip/_vendor/html5lib/constants.py b/pip/_vendor/html5lib/constants.py --- a/pip/_vendor/html5lib/constants.py +++ b/pip/_vendor/html5lib/constants.py @@ -283,6 +283,12 @@ "Element %(name)s not allowed in a non-html context", "unexpected-end-tag-before-html": "Unexpected end tag (%(name)s) before html.", + "unexpected-inhead-noscript-tag": + "Element %(name)s not allowed in a inhead-noscript context", + "eof-in-head-noscript": + "Unexpected end of file. Expected inhead-noscript content", + "char-in-head-noscript": + "Unexpected non-space character. Expected inhead-noscript content", "XXX-undefined-error": "Undefined error (this sucks and should be fixed)", } @@ -431,6 +437,73 @@ (namespaces["mathml"], "mtext") ]) +adjustSVGAttributes = { + "attributename": "attributeName", + "attributetype": "attributeType", + "basefrequency": "baseFrequency", + "baseprofile": "baseProfile", + "calcmode": "calcMode", + "clippathunits": "clipPathUnits", + "contentscripttype": "contentScriptType", + "contentstyletype": "contentStyleType", + "diffuseconstant": "diffuseConstant", + "edgemode": "edgeMode", + "externalresourcesrequired": "externalResourcesRequired", + "filterres": "filterRes", + "filterunits": "filterUnits", + "glyphref": "glyphRef", + "gradienttransform": "gradientTransform", + "gradientunits": "gradientUnits", + "kernelmatrix": "kernelMatrix", + "kernelunitlength": "kernelUnitLength", + "keypoints": "keyPoints", + "keysplines": "keySplines", + "keytimes": "keyTimes", + "lengthadjust": "lengthAdjust", + "limitingconeangle": "limitingConeAngle", + "markerheight": "markerHeight", + "markerunits": "markerUnits", + "markerwidth": "markerWidth", + "maskcontentunits": "maskContentUnits", + "maskunits": "maskUnits", + "numoctaves": "numOctaves", + "pathlength": "pathLength", + "patterncontentunits": "patternContentUnits", + "patterntransform": "patternTransform", + "patternunits": "patternUnits", + "pointsatx": "pointsAtX", + "pointsaty": "pointsAtY", + "pointsatz": "pointsAtZ", + "preservealpha": "preserveAlpha", + "preserveaspectratio": "preserveAspectRatio", + "primitiveunits": "primitiveUnits", + "refx": "refX", + "refy": "refY", + "repeatcount": "repeatCount", + "repeatdur": "repeatDur", + "requiredextensions": "requiredExtensions", + "requiredfeatures": "requiredFeatures", + "specularconstant": "specularConstant", + "specularexponent": "specularExponent", + "spreadmethod": "spreadMethod", + "startoffset": "startOffset", + "stddeviation": "stdDeviation", + "stitchtiles": "stitchTiles", + "surfacescale": "surfaceScale", + "systemlanguage": "systemLanguage", + "tablevalues": "tableValues", + "targetx": "targetX", + "targety": "targetY", + "textlength": "textLength", + "viewbox": "viewBox", + "viewtarget": "viewTarget", + "xchannelselector": "xChannelSelector", + "ychannelselector": "yChannelSelector", + "zoomandpan": "zoomAndPan" +} + +adjustMathMLAttributes = {"definitionurl": "definitionURL"} + adjustForeignAttributes = { "xlink:actuate": ("xlink", "actuate", namespaces["xlink"]), "xlink:arcrole": ("xlink", "arcrole", namespaces["xlink"]), @@ -2813,7 +2886,6 @@ 0x0d: "\u000D", 0x80: "\u20AC", 0x81: "\u0081", - 0x81: "\u0081", 0x82: "\u201A", 0x83: "\u0192", 0x84: "\u201E", @@ -2846,235 +2918,6 @@ 0x9F: "\u0178", } -encodings = { - '437': 'cp437', - '850': 'cp850', - '852': 'cp852', - '855': 'cp855', - '857': 'cp857', - '860': 'cp860', - '861': 'cp861', - '862': 'cp862', - '863': 'cp863', - '865': 'cp865', - '866': 'cp866', - '869': 'cp869', - 'ansix341968': 'ascii', - 'ansix341986': 'ascii', - 'arabic': 'iso8859-6', - 'ascii': 'ascii', - 'asmo708': 'iso8859-6', - 'big5': 'big5', - 'big5hkscs': 'big5hkscs', - 'chinese': 'gbk', - 'cp037': 'cp037', - 'cp1026': 'cp1026', - 'cp154': 'ptcp154', - 'cp367': 'ascii', - 'cp424': 'cp424', - 'cp437': 'cp437', - 'cp500': 'cp500', - 'cp775': 'cp775', - 'cp819': 'windows-1252', - 'cp850': 'cp850', - 'cp852': 'cp852', - 'cp855': 'cp855', - 'cp857': 'cp857', - 'cp860': 'cp860', - 'cp861': 'cp861', - 'cp862': 'cp862', - 'cp863': 'cp863', - 'cp864': 'cp864', - 'cp865': 'cp865', - 'cp866': 'cp866', - 'cp869': 'cp869', - 'cp936': 'gbk', - 'cpgr': 'cp869', - 'cpis': 'cp861', - 'csascii': 'ascii', - 'csbig5': 'big5', - 'cseuckr': 'cp949', - 'cseucpkdfmtjapanese': 'euc_jp', - 'csgb2312': 'gbk', - 'cshproman8': 'hp-roman8', - 'csibm037': 'cp037', - 'csibm1026': 'cp1026', - 'csibm424': 'cp424', - 'csibm500': 'cp500', - 'csibm855': 'cp855', - 'csibm857': 'cp857', - 'csibm860': 'cp860', - 'csibm861': 'cp861', - 'csibm863': 'cp863', - 'csibm864': 'cp864', - 'csibm865': 'cp865', - 'csibm866': 'cp866', - 'csibm869': 'cp869', - 'csiso2022jp': 'iso2022_jp', - 'csiso2022jp2': 'iso2022_jp_2', - 'csiso2022kr': 'iso2022_kr', - 'csiso58gb231280': 'gbk', - 'csisolatin1': 'windows-1252', - 'csisolatin2': 'iso8859-2', - 'csisolatin3': 'iso8859-3', - 'csisolatin4': 'iso8859-4', - 'csisolatin5': 'windows-1254', - 'csisolatin6': 'iso8859-10', - 'csisolatinarabic': 'iso8859-6', - 'csisolatincyrillic': 'iso8859-5', - 'csisolatingreek': 'iso8859-7', - 'csisolatinhebrew': 'iso8859-8', - 'cskoi8r': 'koi8-r', - 'csksc56011987': 'cp949', - 'cspc775baltic': 'cp775', - 'cspc850multilingual': 'cp850', - 'cspc862latinhebrew': 'cp862', - 'cspc8codepage437': 'cp437', - 'cspcp852': 'cp852', - 'csptcp154': 'ptcp154', - 'csshiftjis': 'shift_jis', - 'csunicode11utf7': 'utf-7', - 'cyrillic': 'iso8859-5', - 'cyrillicasian': 'ptcp154', - 'ebcdiccpbe': 'cp500', - 'ebcdiccpca': 'cp037', - 'ebcdiccpch': 'cp500', - 'ebcdiccphe': 'cp424', - 'ebcdiccpnl': 'cp037', - 'ebcdiccpus': 'cp037', - 'ebcdiccpwt': 'cp037', - 'ecma114': 'iso8859-6', - 'ecma118': 'iso8859-7', - 'elot928': 'iso8859-7', - 'eucjp': 'euc_jp', - 'euckr': 'cp949', - 'extendedunixcodepackedformatforjapanese': 'euc_jp', - 'gb18030': 'gb18030', - 'gb2312': 'gbk', - 'gb231280': 'gbk', - 'gbk': 'gbk', - 'greek': 'iso8859-7', - 'greek8': 'iso8859-7', - 'hebrew': 'iso8859-8', - 'hproman8': 'hp-roman8', - 'hzgb2312': 'hz', - 'ibm037': 'cp037', - 'ibm1026': 'cp1026', - 'ibm367': 'ascii', - 'ibm424': 'cp424', - 'ibm437': 'cp437', - 'ibm500': 'cp500', - 'ibm775': 'cp775', - 'ibm819': 'windows-1252', - 'ibm850': 'cp850', - 'ibm852': 'cp852', - 'ibm855': 'cp855', - 'ibm857': 'cp857', - 'ibm860': 'cp860', - 'ibm861': 'cp861', - 'ibm862': 'cp862', - 'ibm863': 'cp863', - 'ibm864': 'cp864', - 'ibm865': 'cp865', - 'ibm866': 'cp866', - 'ibm869': 'cp869', - 'iso2022jp': 'iso2022_jp', - 'iso2022jp2': 'iso2022_jp_2', - 'iso2022kr': 'iso2022_kr', - 'iso646irv1991': 'ascii', - 'iso646us': 'ascii', - 'iso88591': 'windows-1252', - 'iso885910': 'iso8859-10', - 'iso8859101992': 'iso8859-10', - 'iso885911987': 'windows-1252', - 'iso885913': 'iso8859-13', - 'iso885914': 'iso8859-14', - 'iso8859141998': 'iso8859-14', - 'iso885915': 'iso8859-15', - 'iso885916': 'iso8859-16', - 'iso8859162001': 'iso8859-16', - 'iso88592': 'iso8859-2', - 'iso885921987': 'iso8859-2', - 'iso88593': 'iso8859-3', - 'iso885931988': 'iso8859-3', - 'iso88594': 'iso8859-4', - 'iso885941988': 'iso8859-4', - 'iso88595': 'iso8859-5', - 'iso885951988': 'iso8859-5', - 'iso88596': 'iso8859-6', - 'iso885961987': 'iso8859-6', - 'iso88597': 'iso8859-7', - 'iso885971987': 'iso8859-7', - 'iso88598': 'iso8859-8', - 'iso885981988': 'iso8859-8', - 'iso88599': 'windows-1254', - 'iso885991989': 'windows-1254', - 'isoceltic': 'iso8859-14', - 'isoir100': 'windows-1252', - 'isoir101': 'iso8859-2', - 'isoir109': 'iso8859-3', - 'isoir110': 'iso8859-4', - 'isoir126': 'iso8859-7', - 'isoir127': 'iso8859-6', - 'isoir138': 'iso8859-8', - 'isoir144': 'iso8859-5', - 'isoir148': 'windows-1254', - 'isoir149': 'cp949', - 'isoir157': 'iso8859-10', - 'isoir199': 'iso8859-14', - 'isoir226': 'iso8859-16', - 'isoir58': 'gbk', - 'isoir6': 'ascii', - 'koi8r': 'koi8-r', - 'koi8u': 'koi8-u', - 'korean': 'cp949', - 'ksc5601': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'l1': 'windows-1252', - 'l10': 'iso8859-16', - 'l2': 'iso8859-2', - 'l3': 'iso8859-3', - 'l4': 'iso8859-4', - 'l5': 'windows-1254', - 'l6': 'iso8859-10', - 'l8': 'iso8859-14', - 'latin1': 'windows-1252', - 'latin10': 'iso8859-16', - 'latin2': 'iso8859-2', - 'latin3': 'iso8859-3', - 'latin4': 'iso8859-4', - 'latin5': 'windows-1254', - 'latin6': 'iso8859-10', - 'latin8': 'iso8859-14', - 'latin9': 'iso8859-15', - 'ms936': 'gbk', - 'mskanji': 'shift_jis', - 'pt154': 'ptcp154', - 'ptcp154': 'ptcp154', - 'r8': 'hp-roman8', - 'roman8': 'hp-roman8', - 'shiftjis': 'shift_jis', - 'tis620': 'cp874', - 'unicode11utf7': 'utf-7', - 'us': 'ascii', - 'usascii': 'ascii', - 'utf16': 'utf-16', - 'utf16be': 'utf-16-be', - 'utf16le': 'utf-16-le', - 'utf8': 'utf-8', - 'windows1250': 'cp1250', - 'windows1251': 'cp1251', - 'windows1252': 'cp1252', - 'windows1253': 'cp1253', - 'windows1254': 'cp1254', - 'windows1255': 'cp1255', - 'windows1256': 'cp1256', - 'windows1257': 'cp1257', - 'windows1258': 'cp1258', - 'windows936': 'gbk', - 'x-x-big5': 'big5'} - tokenTypes = { "Doctype": 0, "Characters": 1, diff --git a/pip/_vendor/html5lib/filters/alphabeticalattributes.py b/pip/_vendor/html5lib/filters/alphabeticalattributes.py --- a/pip/_vendor/html5lib/filters/alphabeticalattributes.py +++ b/pip/_vendor/html5lib/filters/alphabeticalattributes.py @@ -1,6 +1,6 @@ from __future__ import absolute_import, division, unicode_literals -from . import _base +from . import base try: from collections import OrderedDict @@ -8,9 +8,9 @@ from ordereddict import OrderedDict -class Filter(_base.Filter): +class Filter(base.Filter): def __iter__(self): - for token in _base.Filter.__iter__(self): + for token in base.Filter.__iter__(self): if token["type"] in ("StartTag", "EmptyTag"): attrs = OrderedDict() for name, value in sorted(token["data"].items(), diff --git a/pip/_vendor/html5lib/filters/_base.py b/pip/_vendor/html5lib/filters/base.py similarity index 100% rename from pip/_vendor/html5lib/filters/_base.py rename to pip/_vendor/html5lib/filters/base.py diff --git a/pip/_vendor/html5lib/filters/inject_meta_charset.py b/pip/_vendor/html5lib/filters/inject_meta_charset.py --- a/pip/_vendor/html5lib/filters/inject_meta_charset.py +++ b/pip/_vendor/html5lib/filters/inject_meta_charset.py @@ -1,11 +1,11 @@ from __future__ import absolute_import, division, unicode_literals -from . import _base +from . import base -class Filter(_base.Filter): +class Filter(base.Filter): def __init__(self, source, encoding): - _base.Filter.__init__(self, source) + base.Filter.__init__(self, source) self.encoding = encoding def __iter__(self): @@ -13,7 +13,7 @@ def __iter__(self): meta_found = (self.encoding is None) pending = [] - for token in _base.Filter.__iter__(self): + for token in base.Filter.__iter__(self): type = token["type"] if type == "StartTag": if token["name"].lower() == "head": diff --git a/pip/_vendor/html5lib/filters/lint.py b/pip/_vendor/html5lib/filters/lint.py --- a/pip/_vendor/html5lib/filters/lint.py +++ b/pip/_vendor/html5lib/filters/lint.py @@ -1,90 +1,81 @@ from __future__ import absolute_import, division, unicode_literals -from . import _base -from ..constants import cdataElements, rcdataElements, voidElements +from pip._vendor.six import text_type + +from . import base +from ..constants import namespaces, voidElements from ..constants import spaceCharacters spaceCharacters = "".join(spaceCharacters) -class LintError(Exception): - pass - +class Filter(base.Filter): + def __init__(self, source, require_matching_tags=True): + super(Filter, self).__init__(source) + self.require_matching_tags = require_matching_tags -class Filter(_base.Filter): def __iter__(self): open_elements = [] - contentModelFlag = "PCDATA" - for token in _base.Filter.__iter__(self): + for token in base.Filter.__iter__(self): type = token["type"] if type in ("StartTag", "EmptyTag"): + namespace = token["namespace"] name = token["name"] - if contentModelFlag != "PCDATA": - raise LintError("StartTag not in PCDATA content model flag: %(tag)s" % {"tag": name}) - if not isinstance(name, str): - raise LintError("Tag name is not a string: %(tag)r" % {"tag": name}) - if not name: - raise LintError("Empty tag name") - if type == "StartTag" and name in voidElements: - raise LintError("Void element reported as StartTag token: %(tag)s" % {"tag": name}) - elif type == "EmptyTag" and name not in voidElements: - raise LintError("Non-void element reported as EmptyTag token: %(tag)s" % {"tag": token["name"]}) - if type == "StartTag": - open_elements.append(name) - for name, value in token["data"]: - if not isinstance(name, str): - raise LintError("Attribute name is not a string: %(name)r" % {"name": name}) - if not name: - raise LintError("Empty attribute name") - if not isinstance(value, str): - raise LintError("Attribute value is not a string: %(value)r" % {"value": value}) - if name in cdataElements: - contentModelFlag = "CDATA" - elif name in rcdataElements: - contentModelFlag = "RCDATA" - elif name == "plaintext": - contentModelFlag = "PLAINTEXT" + assert namespace is None or isinstance(namespace, text_type) + assert namespace != "" + assert isinstance(name, text_type) + assert name != "" + assert isinstance(token["data"], dict) + if (not namespace or namespace == namespaces["html"]) and name in voidElements: + assert type == "EmptyTag" + else: + assert type == "StartTag" + if type == "StartTag" and self.require_matching_tags: + open_elements.append((namespace, name)) + for (namespace, name), value in token["data"].items(): + assert namespace is None or isinstance(namespace, text_type) + assert namespace != "" + assert isinstance(name, text_type) + assert name != "" + assert isinstance(value, text_type) elif type == "EndTag": + namespace = token["namespace"] name = token["name"] - if not isinstance(name, str): - raise LintError("Tag name is not a string: %(tag)r" % {"tag": name}) - if not name: - raise LintError("Empty tag name") - if name in voidElements: - raise LintError("Void element reported as EndTag token: %(tag)s" % {"tag": name}) - start_name = open_elements.pop() - if start_name != name: - raise LintError("EndTag (%(end)s) does not match StartTag (%(start)s)" % {"end": name, "start": start_name}) - contentModelFlag = "PCDATA" + assert namespace is None or isinstance(namespace, text_type) + assert namespace != "" + assert isinstance(name, text_type) + assert name != "" + if (not namespace or namespace == namespaces["html"]) and name in voidElements: + assert False, "Void element reported as EndTag token: %(tag)s" % {"tag": name} + elif self.require_matching_tags: + start = open_elements.pop() + assert start == (namespace, name) elif type == "Comment": - if contentModelFlag != "PCDATA": - raise LintError("Comment not in PCDATA content model flag") + data = token["data"] + assert isinstance(data, text_type) elif type in ("Characters", "SpaceCharacters"): data = token["data"] - if not isinstance(data, str): - raise LintError("Attribute name is not a string: %(name)r" % {"name": data}) - if not data: - raise LintError("%(type)s token with empty data" % {"type": type}) + assert isinstance(data, text_type) + assert data != "" if type == "SpaceCharacters": - data = data.strip(spaceCharacters) - if data: - raise LintError("Non-space character(s) found in SpaceCharacters token: %(token)r" % {"token": data}) + assert data.strip(spaceCharacters) == "" elif type == "Doctype": name = token["name"] - if contentModelFlag != "PCDATA": - raise LintError("Doctype not in PCDATA content model flag: %(name)s" % {"name": name}) - if not isinstance(name, str): - raise LintError("Tag name is not a string: %(tag)r" % {"tag": name}) - # XXX: what to do with token["data"] ? + assert name is None or isinstance(name, text_type) + assert token["publicId"] is None or isinstance(name, text_type) + assert token["systemId"] is None or isinstance(name, text_type) + + elif type == "Entity": + assert isinstance(token["name"], text_type) - elif type in ("ParseError", "SerializeError"): - pass + elif type == "SerializerError": + assert isinstance(token["data"], text_type) else: - raise LintError("Unknown token type: %(type)s" % {"type": type}) + assert False, "Unknown token type: %(type)s" % {"type": type} yield token diff --git a/pip/_vendor/html5lib/filters/optionaltags.py b/pip/_vendor/html5lib/filters/optionaltags.py --- a/pip/_vendor/html5lib/filters/optionaltags.py +++ b/pip/_vendor/html5lib/filters/optionaltags.py @@ -1,9 +1,9 @@ from __future__ import absolute_import, division, unicode_literals -from . import _base +from . import base -class Filter(_base.Filter): +class Filter(base.Filter): def slider(self): previous1 = previous2 = None for token in self.source: @@ -11,7 +11,8 @@ def slider(self): yield previous2, previous1, token previous2 = previous1 previous1 = token - yield previous2, previous1, None + if previous1 is not None: + yield previous2, previous1, None def __iter__(self): for previous, token, next in self.slider(): @@ -58,7 +59,7 @@ def is_optional_start(self, tagname, previous, next): elif tagname == 'colgroup': # A colgroup element's start tag may be omitted if the first thing # inside the colgroup element is a col element, and if the element - # is not immediately preceeded by another colgroup element whose + # is not immediately preceded by another colgroup element whose # end tag has been omitted. if type in ("StartTag", "EmptyTag"): # XXX: we do not look at the preceding event, so instead we never @@ -70,7 +71,7 @@ def is_optional_start(self, tagname, previous, next): elif tagname == 'tbody': # A tbody element's start tag may be omitted if the first thing # inside the tbody element is a tr element, and if the element is - # not immediately preceeded by a tbody, thead, or tfoot element + # not immediately preceded by a tbody, thead, or tfoot element # whose end tag has been omitted. if type == "StartTag": # omit the thead and tfoot elements' end tag when they are diff --git a/pip/_vendor/html5lib/filters/sanitizer.py b/pip/_vendor/html5lib/filters/sanitizer.py --- a/pip/_vendor/html5lib/filters/sanitizer.py +++ b/pip/_vendor/html5lib/filters/sanitizer.py @@ -1,12 +1,865 @@ from __future__ import absolute_import, division, unicode_literals -from . import _base -from ..sanitizer import HTMLSanitizerMixin +import re +from xml.sax.saxutils import escape, unescape +from pip._vendor.six.moves import urllib_parse as urlparse + +from . import base +from ..constants import namespaces, prefixes + +__all__ = ["Filter"] + + +allowed_elements = frozenset(( + (namespaces['html'], 'a'), + (namespaces['html'], 'abbr'), + (namespaces['html'], 'acronym'), + (namespaces['html'], 'address'), + (namespaces['html'], 'area'), + (namespaces['html'], 'article'), + (namespaces['html'], 'aside'), + (namespaces['html'], 'audio'), + (namespaces['html'], 'b'), + (namespaces['html'], 'big'), + (namespaces['html'], 'blockquote'), + (namespaces['html'], 'br'), + (namespaces['html'], 'button'), + (namespaces['html'], 'canvas'), + (namespaces['html'], 'caption'), + (namespaces['html'], 'center'), + (namespaces['html'], 'cite'), + (namespaces['html'], 'code'), + (namespaces['html'], 'col'), + (namespaces['html'], 'colgroup'), + (namespaces['html'], 'command'), + (namespaces['html'], 'datagrid'), + (namespaces['html'], 'datalist'), + (namespaces['html'], 'dd'), + (namespaces['html'], 'del'), + (namespaces['html'], 'details'), + (namespaces['html'], 'dfn'), + (namespaces['html'], 'dialog'), + (namespaces['html'], 'dir'), + (namespaces['html'], 'div'), + (namespaces['html'], 'dl'), + (namespaces['html'], 'dt'), + (namespaces['html'], 'em'), + (namespaces['html'], 'event-source'), + (namespaces['html'], 'fieldset'), + (namespaces['html'], 'figcaption'), + (namespaces['html'], 'figure'), + (namespaces['html'], 'footer'), + (namespaces['html'], 'font'), + (namespaces['html'], 'form'), + (namespaces['html'], 'header'), + (namespaces['html'], 'h1'), + (namespaces['html'], 'h2'), + (namespaces['html'], 'h3'), + (namespaces['html'], 'h4'), + (namespaces['html'], 'h5'), + (namespaces['html'], 'h6'), + (namespaces['html'], 'hr'), + (namespaces['html'], 'i'), + (namespaces['html'], 'img'), + (namespaces['html'], 'input'), + (namespaces['html'], 'ins'), + (namespaces['html'], 'keygen'), + (namespaces['html'], 'kbd'), + (namespaces['html'], 'label'), + (namespaces['html'], 'legend'), + (namespaces['html'], 'li'), + (namespaces['html'], 'm'), + (namespaces['html'], 'map'), + (namespaces['html'], 'menu'), + (namespaces['html'], 'meter'), + (namespaces['html'], 'multicol'), + (namespaces['html'], 'nav'), + (namespaces['html'], 'nextid'), + (namespaces['html'], 'ol'), + (namespaces['html'], 'output'), + (namespaces['html'], 'optgroup'), + (namespaces['html'], 'option'), + (namespaces['html'], 'p'), + (namespaces['html'], 'pre'), + (namespaces['html'], 'progress'), + (namespaces['html'], 'q'), + (namespaces['html'], 's'), + (namespaces['html'], 'samp'), + (namespaces['html'], 'section'), + (namespaces['html'], 'select'), + (namespaces['html'], 'small'), + (namespaces['html'], 'sound'), + (namespaces['html'], 'source'), + (namespaces['html'], 'spacer'), + (namespaces['html'], 'span'), + (namespaces['html'], 'strike'), + (namespaces['html'], 'strong'), + (namespaces['html'], 'sub'), + (namespaces['html'], 'sup'), + (namespaces['html'], 'table'), + (namespaces['html'], 'tbody'), + (namespaces['html'], 'td'), + (namespaces['html'], 'textarea'), + (namespaces['html'], 'time'), + (namespaces['html'], 'tfoot'), + (namespaces['html'], 'th'), + (namespaces['html'], 'thead'), + (namespaces['html'], 'tr'), + (namespaces['html'], 'tt'), + (namespaces['html'], 'u'), + (namespaces['html'], 'ul'), + (namespaces['html'], 'var'), + (namespaces['html'], 'video'), + (namespaces['mathml'], 'maction'), + (namespaces['mathml'], 'math'), + (namespaces['mathml'], 'merror'), + (namespaces['mathml'], 'mfrac'), + (namespaces['mathml'], 'mi'), + (namespaces['mathml'], 'mmultiscripts'), + (namespaces['mathml'], 'mn'), + (namespaces['mathml'], 'mo'), + (namespaces['mathml'], 'mover'), + (namespaces['mathml'], 'mpadded'), + (namespaces['mathml'], 'mphantom'), + (namespaces['mathml'], 'mprescripts'), + (namespaces['mathml'], 'mroot'), + (namespaces['mathml'], 'mrow'), + (namespaces['mathml'], 'mspace'), + (namespaces['mathml'], 'msqrt'), + (namespaces['mathml'], 'mstyle'), + (namespaces['mathml'], 'msub'), + (namespaces['mathml'], 'msubsup'), + (namespaces['mathml'], 'msup'), + (namespaces['mathml'], 'mtable'), + (namespaces['mathml'], 'mtd'), + (namespaces['mathml'], 'mtext'), + (namespaces['mathml'], 'mtr'), + (namespaces['mathml'], 'munder'), + (namespaces['mathml'], 'munderover'), + (namespaces['mathml'], 'none'), + (namespaces['svg'], 'a'), + (namespaces['svg'], 'animate'), + (namespaces['svg'], 'animateColor'), + (namespaces['svg'], 'animateMotion'), + (namespaces['svg'], 'animateTransform'), + (namespaces['svg'], 'clipPath'), + (namespaces['svg'], 'circle'), + (namespaces['svg'], 'defs'), + (namespaces['svg'], 'desc'), + (namespaces['svg'], 'ellipse'), + (namespaces['svg'], 'font-face'), + (namespaces['svg'], 'font-face-name'), + (namespaces['svg'], 'font-face-src'), + (namespaces['svg'], 'g'), + (namespaces['svg'], 'glyph'), + (namespaces['svg'], 'hkern'), + (namespaces['svg'], 'linearGradient'), + (namespaces['svg'], 'line'), + (namespaces['svg'], 'marker'), + (namespaces['svg'], 'metadata'), + (namespaces['svg'], 'missing-glyph'), + (namespaces['svg'], 'mpath'), + (namespaces['svg'], 'path'), + (namespaces['svg'], 'polygon'), + (namespaces['svg'], 'polyline'), + (namespaces['svg'], 'radialGradient'), + (namespaces['svg'], 'rect'), + (namespaces['svg'], 'set'), + (namespaces['svg'], 'stop'), + (namespaces['svg'], 'svg'), + (namespaces['svg'], 'switch'), + (namespaces['svg'], 'text'), + (namespaces['svg'], 'title'), + (namespaces['svg'], 'tspan'), + (namespaces['svg'], 'use'), +)) + +allowed_attributes = frozenset(( + # HTML attributes + (None, 'abbr'), + (None, 'accept'), + (None, 'accept-charset'), + (None, 'accesskey'), + (None, 'action'), + (None, 'align'), + (None, 'alt'), + (None, 'autocomplete'), + (None, 'autofocus'), + (None, 'axis'), + (None, 'background'), + (None, 'balance'), + (None, 'bgcolor'), + (None, 'bgproperties'), + (None, 'border'), + (None, 'bordercolor'), + (None, 'bordercolordark'), + (None, 'bordercolorlight'), + (None, 'bottompadding'), + (None, 'cellpadding'), + (None, 'cellspacing'), + (None, 'ch'), + (None, 'challenge'), + (None, 'char'), + (None, 'charoff'), + (None, 'choff'), + (None, 'charset'), + (None, 'checked'), + (None, 'cite'), + (None, 'class'), + (None, 'clear'), + (None, 'color'), + (None, 'cols'), + (None, 'colspan'), + (None, 'compact'), + (None, 'contenteditable'), + (None, 'controls'), + (None, 'coords'), + (None, 'data'), + (None, 'datafld'), + (None, 'datapagesize'), + (None, 'datasrc'), + (None, 'datetime'), + (None, 'default'), + (None, 'delay'), + (None, 'dir'), + (None, 'disabled'), + (None, 'draggable'), + (None, 'dynsrc'), + (None, 'enctype'), + (None, 'end'), + (None, 'face'), + (None, 'for'), + (None, 'form'), + (None, 'frame'), + (None, 'galleryimg'), + (None, 'gutter'), + (None, 'headers'), + (None, 'height'), + (None, 'hidefocus'), + (None, 'hidden'), + (None, 'high'), + (None, 'href'), + (None, 'hreflang'), + (None, 'hspace'), + (None, 'icon'), + (None, 'id'), + (None, 'inputmode'), + (None, 'ismap'), + (None, 'keytype'), + (None, 'label'), + (None, 'leftspacing'), + (None, 'lang'), + (None, 'list'), + (None, 'longdesc'), + (None, 'loop'), + (None, 'loopcount'), + (None, 'loopend'), + (None, 'loopstart'), + (None, 'low'), + (None, 'lowsrc'), + (None, 'max'), + (None, 'maxlength'), + (None, 'media'), + (None, 'method'), + (None, 'min'), + (None, 'multiple'), + (None, 'name'), + (None, 'nohref'), + (None, 'noshade'), + (None, 'nowrap'), + (None, 'open'), + (None, 'optimum'), + (None, 'pattern'), + (None, 'ping'), + (None, 'point-size'), + (None, 'poster'), + (None, 'pqg'), + (None, 'preload'), + (None, 'prompt'), + (None, 'radiogroup'), + (None, 'readonly'), + (None, 'rel'), + (None, 'repeat-max'), + (None, 'repeat-min'), + (None, 'replace'), + (None, 'required'), + (None, 'rev'), + (None, 'rightspacing'), + (None, 'rows'), + (None, 'rowspan'), + (None, 'rules'), + (None, 'scope'), + (None, 'selected'), + (None, 'shape'), + (None, 'size'), + (None, 'span'), + (None, 'src'), + (None, 'start'), + (None, 'step'), + (None, 'style'), + (None, 'summary'), + (None, 'suppress'), + (None, 'tabindex'), + (None, 'target'), + (None, 'template'), + (None, 'title'), + (None, 'toppadding'), + (None, 'type'), + (None, 'unselectable'), + (None, 'usemap'), + (None, 'urn'), + (None, 'valign'), + (None, 'value'), + (None, 'variable'), + (None, 'volume'), + (None, 'vspace'), + (None, 'vrml'), + (None, 'width'), + (None, 'wrap'), + (namespaces['xml'], 'lang'), + # MathML attributes + (None, 'actiontype'), + (None, 'align'), + (None, 'columnalign'), + (None, 'columnalign'), + (None, 'columnalign'), + (None, 'columnlines'), + (None, 'columnspacing'), + (None, 'columnspan'), + (None, 'depth'), + (None, 'display'), + (None, 'displaystyle'), + (None, 'equalcolumns'), + (None, 'equalrows'), + (None, 'fence'), + (None, 'fontstyle'), + (None, 'fontweight'), + (None, 'frame'), + (None, 'height'), + (None, 'linethickness'), + (None, 'lspace'), + (None, 'mathbackground'), + (None, 'mathcolor'), + (None, 'mathvariant'), + (None, 'mathvariant'), + (None, 'maxsize'), + (None, 'minsize'), + (None, 'other'), + (None, 'rowalign'), + (None, 'rowalign'), + (None, 'rowalign'), + (None, 'rowlines'), + (None, 'rowspacing'), + (None, 'rowspan'), + (None, 'rspace'), + (None, 'scriptlevel'), + (None, 'selection'), + (None, 'separator'), + (None, 'stretchy'), + (None, 'width'), + (None, 'width'), + (namespaces['xlink'], 'href'), + (namespaces['xlink'], 'show'), + (namespaces['xlink'], 'type'), + # SVG attributes + (None, 'accent-height'), + (None, 'accumulate'), + (None, 'additive'), + (None, 'alphabetic'), + (None, 'arabic-form'), + (None, 'ascent'), + (None, 'attributeName'), + (None, 'attributeType'), + (None, 'baseProfile'), + (None, 'bbox'), + (None, 'begin'), + (None, 'by'), + (None, 'calcMode'), + (None, 'cap-height'), + (None, 'class'), + (None, 'clip-path'), + (None, 'color'), + (None, 'color-rendering'), + (None, 'content'), + (None, 'cx'), + (None, 'cy'), + (None, 'd'), + (None, 'dx'), + (None, 'dy'), + (None, 'descent'), + (None, 'display'), + (None, 'dur'), + (None, 'end'), + (None, 'fill'), + (None, 'fill-opacity'), + (None, 'fill-rule'), + (None, 'font-family'), + (None, 'font-size'), + (None, 'font-stretch'), + (None, 'font-style'), + (None, 'font-variant'), + (None, 'font-weight'), + (None, 'from'), + (None, 'fx'), + (None, 'fy'), + (None, 'g1'), + (None, 'g2'), + (None, 'glyph-name'), + (None, 'gradientUnits'), + (None, 'hanging'), + (None, 'height'), + (None, 'horiz-adv-x'), + (None, 'horiz-origin-x'), + (None, 'id'), + (None, 'ideographic'), + (None, 'k'), + (None, 'keyPoints'), + (None, 'keySplines'), + (None, 'keyTimes'), + (None, 'lang'), + (None, 'marker-end'), + (None, 'marker-mid'), + (None, 'marker-start'), + (None, 'markerHeight'), + (None, 'markerUnits'), + (None, 'markerWidth'), + (None, 'mathematical'), + (None, 'max'), + (None, 'min'), + (None, 'name'), + (None, 'offset'), + (None, 'opacity'), + (None, 'orient'), + (None, 'origin'), + (None, 'overline-position'), + (None, 'overline-thickness'), + (None, 'panose-1'), + (None, 'path'), + (None, 'pathLength'), + (None, 'points'), + (None, 'preserveAspectRatio'), + (None, 'r'), + (None, 'refX'), + (None, 'refY'), + (None, 'repeatCount'), + (None, 'repeatDur'), + (None, 'requiredExtensions'), + (None, 'requiredFeatures'), + (None, 'restart'), + (None, 'rotate'), + (None, 'rx'), + (None, 'ry'), + (None, 'slope'), + (None, 'stemh'), + (None, 'stemv'), + (None, 'stop-color'), + (None, 'stop-opacity'), + (None, 'strikethrough-position'), + (None, 'strikethrough-thickness'), + (None, 'stroke'), + (None, 'stroke-dasharray'), + (None, 'stroke-dashoffset'), + (None, 'stroke-linecap'), + (None, 'stroke-linejoin'), + (None, 'stroke-miterlimit'), + (None, 'stroke-opacity'), + (None, 'stroke-width'), + (None, 'systemLanguage'), + (None, 'target'), + (None, 'text-anchor'), + (None, 'to'), + (None, 'transform'), + (None, 'type'), + (None, 'u1'), + (None, 'u2'), + (None, 'underline-position'), + (None, 'underline-thickness'), + (None, 'unicode'), + (None, 'unicode-range'), + (None, 'units-per-em'), + (None, 'values'), + (None, 'version'), + (None, 'viewBox'), + (None, 'visibility'), + (None, 'width'), + (None, 'widths'), + (None, 'x'), + (None, 'x-height'), + (None, 'x1'), + (None, 'x2'), + (namespaces['xlink'], 'actuate'), + (namespaces['xlink'], 'arcrole'), + (namespaces['xlink'], 'href'), + (namespaces['xlink'], 'role'), + (namespaces['xlink'], 'show'), + (namespaces['xlink'], 'title'), + (namespaces['xlink'], 'type'), + (namespaces['xml'], 'base'), + (namespaces['xml'], 'lang'), + (namespaces['xml'], 'space'), + (None, 'y'), + (None, 'y1'), + (None, 'y2'), + (None, 'zoomAndPan'), +)) + +attr_val_is_uri = frozenset(( + (None, 'href'), + (None, 'src'), + (None, 'cite'), + (None, 'action'), + (None, 'longdesc'), + (None, 'poster'), + (None, 'background'), + (None, 'datasrc'), + (None, 'dynsrc'), + (None, 'lowsrc'), + (None, 'ping'), + (namespaces['xlink'], 'href'), + (namespaces['xml'], 'base'), +)) + +svg_attr_val_allows_ref = frozenset(( + (None, 'clip-path'), + (None, 'color-profile'), + (None, 'cursor'), + (None, 'fill'), + (None, 'filter'), + (None, 'marker'), + (None, 'marker-start'), + (None, 'marker-mid'), + (None, 'marker-end'), + (None, 'mask'), + (None, 'stroke'), +)) + +svg_allow_local_href = frozenset(( + (None, 'altGlyph'), + (None, 'animate'), + (None, 'animateColor'), + (None, 'animateMotion'), + (None, 'animateTransform'), + (None, 'cursor'), + (None, 'feImage'), + (None, 'filter'), + (None, 'linearGradient'), + (None, 'pattern'), + (None, 'radialGradient'), + (None, 'textpath'), + (None, 'tref'), + (None, 'set'), + (None, 'use') +)) + +allowed_css_properties = frozenset(( + 'azimuth', + 'background-color', + 'border-bottom-color', + 'border-collapse', + 'border-color', + 'border-left-color', + 'border-right-color', + 'border-top-color', + 'clear', + 'color', + 'cursor', + 'direction', + 'display', + 'elevation', + 'float', + 'font', + 'font-family', + 'font-size', + 'font-style', + 'font-variant', + 'font-weight', + 'height', + 'letter-spacing', + 'line-height', + 'overflow', + 'pause', + 'pause-after', + 'pause-before', + 'pitch', + 'pitch-range', + 'richness', + 'speak', + 'speak-header', + 'speak-numeral', + 'speak-punctuation', + 'speech-rate', + 'stress', + 'text-align', + 'text-decoration', + 'text-indent', + 'unicode-bidi', + 'vertical-align', + 'voice-family', + 'volume', + 'white-space', + 'width', +)) + +allowed_css_keywords = frozenset(( + 'auto', + 'aqua', + 'black', + 'block', + 'blue', + 'bold', + 'both', + 'bottom', + 'brown', + 'center', + 'collapse', + 'dashed', + 'dotted', + 'fuchsia', + 'gray', + 'green', + '!important', + 'italic', + 'left', + 'lime', + 'maroon', + 'medium', + 'none', + 'navy', + 'normal', + 'nowrap', + 'olive', + 'pointer', + 'purple', + 'red', + 'right', + 'solid', + 'silver', + 'teal', + 'top', + 'transparent', + 'underline', + 'white', + 'yellow', +)) + +allowed_svg_properties = frozenset(( + 'fill', + 'fill-opacity', + 'fill-rule', + 'stroke', + 'stroke-width', + 'stroke-linecap', + 'stroke-linejoin', + 'stroke-opacity', +)) + +allowed_protocols = frozenset(( + 'ed2k', + 'ftp', + 'http', + 'https', + 'irc', + 'mailto', + 'news', + 'gopher', + 'nntp', + 'telnet', + 'webcal', + 'xmpp', + 'callto', + 'feed', + 'urn', + 'aim', + 'rsync', + 'tag', + 'ssh', + 'sftp', + 'rtsp', + 'afs', + 'data', +)) + +allowed_content_types = frozenset(( + 'image/png', + 'image/jpeg', + 'image/gif', + 'image/webp', + 'image/bmp', + 'text/plain', +)) + + +data_content_type = re.compile(r''' + ^ + # Match a content type <application>/<type> + (?P<content_type>[-a-zA-Z0-9.]+/[-a-zA-Z0-9.]+) + # Match any character set and encoding + (?:(?:;charset=(?:[-a-zA-Z0-9]+)(?:;(?:base64))?) + |(?:;(?:base64))?(?:;charset=(?:[-a-zA-Z0-9]+))?) + # Assume the rest is data + ,.* + $ + ''', + re.VERBOSE) + + +class Filter(base.Filter): + """ sanitization of XHTML+MathML+SVG and of inline style attributes.""" + def __init__(self, + source, + allowed_elements=allowed_elements, + allowed_attributes=allowed_attributes, + allowed_css_properties=allowed_css_properties, + allowed_css_keywords=allowed_css_keywords, + allowed_svg_properties=allowed_svg_properties, + allowed_protocols=allowed_protocols, + allowed_content_types=allowed_content_types, + attr_val_is_uri=attr_val_is_uri, + svg_attr_val_allows_ref=svg_attr_val_allows_ref, + svg_allow_local_href=svg_allow_local_href): + super(Filter, self).__init__(source) + self.allowed_elements = allowed_elements + self.allowed_attributes = allowed_attributes + self.allowed_css_properties = allowed_css_properties + self.allowed_css_keywords = allowed_css_keywords + self.allowed_svg_properties = allowed_svg_properties + self.allowed_protocols = allowed_protocols + self.allowed_content_types = allowed_content_types + self.attr_val_is_uri = attr_val_is_uri + self.svg_attr_val_allows_ref = svg_attr_val_allows_ref + self.svg_allow_local_href = svg_allow_local_href -class Filter(_base.Filter, HTMLSanitizerMixin): def __iter__(self): - for token in _base.Filter.__iter__(self): + for token in base.Filter.__iter__(self): token = self.sanitize_token(token) if token: yield token + + # Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and + # stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style + # attributes are parsed, and a restricted set, # specified by + # ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through. + # attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified + # in ALLOWED_PROTOCOLS are allowed. + # + # sanitize_html('<script> do_nasty_stuff() </script>') + # => &lt;script> do_nasty_stuff() &lt;/script> + # sanitize_html('<a href="javascript: sucker();">Click here for $100</a>') + # => <a>Click here for $100</a> + def sanitize_token(self, token): + + # accommodate filters which use token_type differently + token_type = token["type"] + if token_type in ("StartTag", "EndTag", "EmptyTag"): + name = token["name"] + namespace = token["namespace"] + if ((namespace, name) in self.allowed_elements or + (namespace is None and + (namespaces["html"], name) in self.allowed_elements)): + return self.allowed_token(token) + else: + return self.disallowed_token(token) + elif token_type == "Comment": + pass + else: + return token + + def allowed_token(self, token): + if "data" in token: + attrs = token["data"] + attr_names = set(attrs.keys()) + + # Remove forbidden attributes + for to_remove in (attr_names - self.allowed_attributes): + del token["data"][to_remove] + attr_names.remove(to_remove) + + # Remove attributes with disallowed URL values + for attr in (attr_names & self.attr_val_is_uri): + assert attr in attrs + # I don't have a clue where this regexp comes from or why it matches those + # characters, nor why we call unescape. I just know it's always been here. + # Should you be worried by this comment in a sanitizer? Yes. On the other hand, all + # this will do is remove *more* than it otherwise would. + val_unescaped = re.sub("[`\x00-\x20\x7f-\xa0\s]+", '', + unescape(attrs[attr])).lower() + # remove replacement characters from unescaped characters + val_unescaped = val_unescaped.replace("\ufffd", "") + try: + uri = urlparse.urlparse(val_unescaped) + except ValueError: + uri = None + del attrs[attr] + if uri and uri.scheme: + if uri.scheme not in self.allowed_protocols: + del attrs[attr] + if uri.scheme == 'data': + m = data_content_type.match(uri.path) + if not m: + del attrs[attr] + elif m.group('content_type') not in self.allowed_content_types: + del attrs[attr] + + for attr in self.svg_attr_val_allows_ref: + if attr in attrs: + attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', + ' ', + unescape(attrs[attr])) + if (token["name"] in self.svg_allow_local_href and + (namespaces['xlink'], 'href') in attrs and re.search('^\s*[^#\s].*', + attrs[(namespaces['xlink'], 'href')])): + del attrs[(namespaces['xlink'], 'href')] + if (None, 'style') in attrs: + attrs[(None, 'style')] = self.sanitize_css(attrs[(None, 'style')]) + token["data"] = attrs + return token + + def disallowed_token(self, token): + token_type = token["type"] + if token_type == "EndTag": + token["data"] = "</%s>" % token["name"] + elif token["data"]: + assert token_type in ("StartTag", "EmptyTag") + attrs = [] + for (ns, name), v in token["data"].items(): + attrs.append(' %s="%s"' % (name if ns is None else "%s:%s" % (prefixes[ns], name), escape(v))) + token["data"] = "<%s%s>" % (token["name"], ''.join(attrs)) + else: + token["data"] = "<%s>" % token["name"] + if token.get("selfClosing"): + token["data"] = token["data"][:-1] + "/>" + + token["type"] = "Characters" + + del token["name"] + return token + + def sanitize_css(self, style): + # disallow urls + style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) + + # gauntlet + if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): + return '' + if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): + return '' + + clean = [] + for prop, value in re.findall("([-\w]+)\s*:\s*([^:;]*)", style): + if not value: + continue + if prop.lower() in self.allowed_css_properties: + clean.append(prop + ': ' + value + ';') + elif prop.split('-')[0].lower() in ['background', 'border', 'margin', + 'padding']: + for keyword in value.split(): + if keyword not in self.allowed_css_keywords and \ + not re.match("^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$", keyword): # noqa + break + else: + clean.append(prop + ': ' + value + ';') + elif prop.lower() in self.allowed_svg_properties: + clean.append(prop + ': ' + value + ';') + + return ' '.join(clean) diff --git a/pip/_vendor/html5lib/filters/whitespace.py b/pip/_vendor/html5lib/filters/whitespace.py --- a/pip/_vendor/html5lib/filters/whitespace.py +++ b/pip/_vendor/html5lib/filters/whitespace.py @@ -2,20 +2,20 @@ import re -from . import _base +from . import base from ..constants import rcdataElements, spaceCharacters spaceCharacters = "".join(spaceCharacters) SPACES_REGEX = re.compile("[%s]+" % spaceCharacters) -class Filter(_base.Filter): +class Filter(base.Filter): spacePreserveElements = frozenset(["pre", "textarea"] + list(rcdataElements)) def __iter__(self): preserve = 0 - for token in _base.Filter.__iter__(self): + for token in base.Filter.__iter__(self): type = token["type"] if type == "StartTag" \ and (preserve or token["name"] in self.spacePreserveElements): diff --git a/pip/_vendor/html5lib/html5parser.py b/pip/_vendor/html5lib/html5parser.py --- a/pip/_vendor/html5lib/html5parser.py +++ b/pip/_vendor/html5lib/html5parser.py @@ -1,39 +1,44 @@ from __future__ import absolute_import, division, unicode_literals -from pip._vendor.six import with_metaclass +from pip._vendor.six import with_metaclass, viewkeys, PY3 import types -from . import inputstream -from . import tokenizer +try: + from collections import OrderedDict +except ImportError: + from pip._vendor.ordereddict import OrderedDict + +from . import _inputstream +from . import _tokenizer from . import treebuilders -from .treebuilders._base import Marker - -from . import utils -from . import constants -from .constants import spaceCharacters, asciiUpper2Lower -from .constants import specialElements -from .constants import headingElements -from .constants import cdataElements, rcdataElements -from .constants import tokenTypes, ReparseException, namespaces -from .constants import htmlIntegrationPointElements, mathmlTextIntegrationPointElements -from .constants import adjustForeignAttributes as adjustForeignAttributesMap -from .constants import E - - -def parse(doc, treebuilder="etree", encoding=None, - namespaceHTMLElements=True): +from .treebuilders.base import Marker + +from . import _utils +from .constants import ( + spaceCharacters, asciiUpper2Lower, + specialElements, headingElements, cdataElements, rcdataElements, + tokenTypes, tagTokenTypes, + namespaces, + htmlIntegrationPointElements, mathmlTextIntegrationPointElements, + adjustForeignAttributes as adjustForeignAttributesMap, + adjustMathMLAttributes, adjustSVGAttributes, + E, + ReparseException +) + + +def parse(doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs): """Parse a string or file-like object into a tree""" tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) - return p.parse(doc, encoding=encoding) + return p.parse(doc, **kwargs) -def parseFragment(doc, container="div", treebuilder="etree", encoding=None, - namespaceHTMLElements=True): +def parseFragment(doc, container="div", treebuilder="etree", namespaceHTMLElements=True, **kwargs): tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) - return p.parseFragment(doc, container=container, encoding=encoding) + return p.parseFragment(doc, container=container, **kwargs) def method_decorator_metaclass(function): @@ -52,18 +57,13 @@ class HTMLParser(object): """HTML parser. Generates a tree structure from a stream of (possibly malformed) HTML""" - def __init__(self, tree=None, tokenizer=tokenizer.HTMLTokenizer, - strict=False, namespaceHTMLElements=True, debug=False): + def __init__(self, tree=None, strict=False, namespaceHTMLElements=True, debug=False): """ strict - raise an exception when a parse error is encountered tree - a treebuilder class controlling the type of tree that will be returned. Built in treebuilders can be accessed through html5lib.treebuilders.getTreeBuilder(treeType) - - tokenizer - a class that provides a stream of tokens to the treebuilder. - This may be replaced for e.g. a sanitizer which converts some tags to - text """ # Raise an exception on the first error encountered @@ -72,29 +72,24 @@ def __init__(self, tree=None, tokenizer=tokenizer.HTMLTokenizer, if tree is None: tree = treebuilders.getTreeBuilder("etree") self.tree = tree(namespaceHTMLElements) - self.tokenizer_class = tokenizer self.errors = [] self.phases = dict([(name, cls(self, self.tree)) for name, cls in getPhases(debug).items()]) - def _parse(self, stream, innerHTML=False, container="div", - encoding=None, parseMeta=True, useChardet=True, **kwargs): + def _parse(self, stream, innerHTML=False, container="div", scripting=False, **kwargs): self.innerHTMLMode = innerHTML self.container = container - self.tokenizer = self.tokenizer_class(stream, encoding=encoding, - parseMeta=parseMeta, - useChardet=useChardet, - parser=self, **kwargs) + self.scripting = scripting + self.tokenizer = _tokenizer.HTMLTokenizer(stream, parser=self, **kwargs) self.reset() - while True: - try: - self.mainLoop() - break - except ReparseException: - self.reset() + try: + self.mainLoop() + except ReparseException: + self.reset() + self.mainLoop() def reset(self): self.tree.reset() @@ -121,7 +116,7 @@ def reset(self): self.phase.insertHtmlElement() self.resetInsertionMode() else: - self.innerHTML = False + self.innerHTML = False # pylint:disable=redefined-variable-type self.phase = self.phases["initial"] self.lastPhase = None @@ -139,7 +134,7 @@ def documentEncoding(self): """ if not hasattr(self, 'tokenizer'): return None - return self.tokenizer.stream.charEncoding[0] + return self.tokenizer.stream.charEncoding[0].name def isHTMLIntegrationPoint(self, element): if (element.name == "annotation-xml" and @@ -164,8 +159,10 @@ def mainLoop(self): ParseErrorToken = tokenTypes["ParseError"] for token in self.normalizedTokens(): + prev_token = None new_token = token while new_token is not None: + prev_token = new_token currentNode = self.tree.openElements[-1] if self.tree.openElements else None currentNodeNamespace = currentNode.namespace if currentNode else None currentNodeName = currentNode.name if currentNode else None @@ -184,6 +181,7 @@ def mainLoop(self): type in (CharactersToken, SpaceCharactersToken))) or (currentNodeNamespace == namespaces["mathml"] and currentNodeName == "annotation-xml" and + type == StartTagToken and token["name"] == "svg") or (self.isHTMLIntegrationPoint(currentNode) and type in (StartTagToken, CharactersToken, SpaceCharactersToken))): @@ -204,10 +202,10 @@ def mainLoop(self): elif type == DoctypeToken: new_token = phase.processDoctype(new_token) - if (type == StartTagToken and token["selfClosing"] - and not token["selfClosingAcknowledged"]): + if (type == StartTagToken and prev_token["selfClosing"] and + not prev_token["selfClosingAcknowledged"]): self.parseError("non-void-element-with-trailing-solidus", - {"name": token["name"]}) + {"name": prev_token["name"]}) # When the loop finishes it's EOF reprocess = True @@ -222,7 +220,7 @@ def normalizedTokens(self): for token in self.tokenizer: yield self.normalizeToken(token) - def parse(self, stream, encoding=None, parseMeta=True, useChardet=True): + def parse(self, stream, *args, **kwargs): """Parse a HTML document into a well-formed tree stream - a filelike object or string containing the HTML to be parsed @@ -231,13 +229,13 @@ def parse(self, stream, encoding=None, parseMeta=True, useChardet=True): the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) + + scripting - treat noscript elements as if javascript was turned on """ - self._parse(stream, innerHTML=False, encoding=encoding, - parseMeta=parseMeta, useChardet=useChardet) + self._parse(stream, False, None, *args, **kwargs) return self.tree.getDocument() - def parseFragment(self, stream, container="div", encoding=None, - parseMeta=False, useChardet=True): + def parseFragment(self, stream, *args, **kwargs): """Parse a HTML fragment into a well-formed tree fragment container - name of the element we're setting the innerHTML property @@ -249,12 +247,16 @@ def parseFragment(self, stream, container="div", encoding=None, the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) + + scripting - treat noscript elements as if javascript was turned on """ - self._parse(stream, True, container=container, encoding=encoding) + self._parse(stream, True, *args, **kwargs) return self.tree.getFragment() - def parseError(self, errorcode="XXX-undefined-error", datavars={}): + def parseError(self, errorcode="XXX-undefined-error", datavars=None): # XXX The idea is to make errorcode mandatory. + if datavars is None: + datavars = {} self.errors.append((self.tokenizer.stream.position(), errorcode, datavars)) if self.strict: raise ParseError(E[errorcode] % datavars) @@ -263,98 +265,25 @@ def normalizeToken(self, token): """ HTML5 specific normalizations to the token stream """ if token["type"] == tokenTypes["StartTag"]: - token["data"] = dict(token["data"][::-1]) + raw = token["data"] + token["data"] = OrderedDict(raw) + if len(raw) > len(token["data"]): + # we had some duplicated attribute, fix so first wins + token["data"].update(raw[::-1]) return token def adjustMathMLAttributes(self, token): - replacements = {"definitionurl": "definitionURL"} - for k, v in replacements.items(): - if k in token["data"]: - token["data"][v] = token["data"][k] - del token["data"][k] + adjust_attributes(token, adjustMathMLAttributes) def adjustSVGAttributes(self, token): - replacements = { - "attributename": "attributeName", - "attributetype": "attributeType", - "basefrequency": "baseFrequency", - "baseprofile": "baseProfile", - "calcmode": "calcMode", - "clippathunits": "clipPathUnits", - "contentscripttype": "contentScriptType", - "contentstyletype": "contentStyleType", - "diffuseconstant": "diffuseConstant", - "edgemode": "edgeMode", - "externalresourcesrequired": "externalResourcesRequired", - "filterres": "filterRes", - "filterunits": "filterUnits", - "glyphref": "glyphRef", - "gradienttransform": "gradientTransform", - "gradientunits": "gradientUnits", - "kernelmatrix": "kernelMatrix", - "kernelunitlength": "kernelUnitLength", - "keypoints": "keyPoints", - "keysplines": "keySplines", - "keytimes": "keyTimes", - "lengthadjust": "lengthAdjust", - "limitingconeangle": "limitingConeAngle", - "markerheight": "markerHeight", - "markerunits": "markerUnits", - "markerwidth": "markerWidth", - "maskcontentunits": "maskContentUnits", - "maskunits": "maskUnits", - "numoctaves": "numOctaves", - "pathlength": "pathLength", - "patterncontentunits": "patternContentUnits", - "patterntransform": "patternTransform", - "patternunits": "patternUnits", - "pointsatx": "pointsAtX", - "pointsaty": "pointsAtY", - "pointsatz": "pointsAtZ", - "preservealpha": "preserveAlpha", - "preserveaspectratio": "preserveAspectRatio", - "primitiveunits": "primitiveUnits", - "refx": "refX", - "refy": "refY", - "repeatcount": "repeatCount", - "repeatdur": "repeatDur", - "requiredextensions": "requiredExtensions", - "requiredfeatures": "requiredFeatures", - "specularconstant": "specularConstant", - "specularexponent": "specularExponent", - "spreadmethod": "spreadMethod", - "startoffset": "startOffset", - "stddeviation": "stdDeviation", - "stitchtiles": "stitchTiles", - "surfacescale": "surfaceScale", - "systemlanguage": "systemLanguage", - "tablevalues": "tableValues", - "targetx": "targetX", - "targety": "targetY", - "textlength": "textLength", - "viewbox": "viewBox", - "viewtarget": "viewTarget", - "xchannelselector": "xChannelSelector", - "ychannelselector": "yChannelSelector", - "zoomandpan": "zoomAndPan" - } - for originalName in list(token["data"].keys()): - if originalName in replacements: - svgName = replacements[originalName] - token["data"][svgName] = token["data"][originalName] - del token["data"][originalName] + adjust_attributes(token, adjustSVGAttributes) def adjustForeignAttributes(self, token): - replacements = adjustForeignAttributesMap - - for originalName in token["data"].keys(): - if originalName in replacements: - foreignName = replacements[originalName] - token["data"][foreignName] = token["data"][originalName] - del token["data"][originalName] + adjust_attributes(token, adjustForeignAttributesMap) def reparseTokenNormal(self, token): + # pylint:disable=unused-argument self.parser.phase() def resetInsertionMode(self): @@ -419,11 +348,12 @@ def parseRCDataRawtext(self, token, contentType): self.phase = self.phases["text"] +@_utils.memoize 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()) + tokenTypes.items()) def wrapped(self, *args, **kwargs): if function.__name__.startswith("process") and len(args) > 0: @@ -432,7 +362,7 @@ def wrapped(self, *args, **kwargs): info = {"type": type_names[token['type']]} except: raise - if token['type'] in constants.tagTokenTypes: + if token['type'] in tagTokenTypes: info["name"] = token['name'] self.parser.log.append((self.parser.tokenizer.state.__name__, @@ -451,6 +381,7 @@ def getMetaclass(use_metaclass, metaclass_func): else: return type + # pylint:disable=unused-argument class Phase(with_metaclass(getMetaclass(debug, log))): """Base class for helper object that implements each phase of processing """ @@ -517,77 +448,76 @@ def processDoctype(self, token): if publicId != "": publicId = publicId.translate(asciiUpper2Lower) - if (not correct or token["name"] != "html" - or publicId.startswith( - ("+//silmaril//dtd html pro v0r11 19970101//", - "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", - "-//as//dtd html 3.0 aswedit + extensions//", - "-//ietf//dtd html 2.0 level 1//", - "-//ietf//dtd html 2.0 level 2//", - "-//ietf//dtd html 2.0 strict level 1//", - "-//ietf//dtd html 2.0 strict level 2//", - "-//ietf//dtd html 2.0 strict//", - "-//ietf//dtd html 2.0//", - "-//ietf//dtd html 2.1e//", - "-//ietf//dtd html 3.0//", - "-//ietf//dtd html 3.2 final//", - "-//ietf//dtd html 3.2//", - "-//ietf//dtd html 3//", - "-//ietf//dtd html level 0//", - "-//ietf//dtd html level 1//", - "-//ietf//dtd html level 2//", - "-//ietf//dtd html level 3//", - "-//ietf//dtd html strict level 0//", - "-//ietf//dtd html strict level 1//", - "-//ietf//dtd html strict level 2//", - "-//ietf//dtd html strict level 3//", - "-//ietf//dtd html strict//", - "-//ietf//dtd html//", - "-//metrius//dtd metrius presentational//", - "-//microsoft//dtd internet explorer 2.0 html strict//", - "-//microsoft//dtd internet explorer 2.0 html//", - "-//microsoft//dtd internet explorer 2.0 tables//", - "-//microsoft//dtd internet explorer 3.0 html strict//", - "-//microsoft//dtd internet explorer 3.0 html//", - "-//microsoft//dtd internet explorer 3.0 tables//", - "-//netscape comm. corp.//dtd html//", - "-//netscape comm. corp.//dtd strict html//", - "-//o'reilly and associates//dtd html 2.0//", - "-//o'reilly and associates//dtd html extended 1.0//", - "-//o'reilly and associates//dtd html extended relaxed 1.0//", - "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", - "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", - "-//spyglass//dtd html 2.0 extended//", - "-//sq//dtd html 2.0 hotmetal + extensions//", - "-//sun microsystems corp.//dtd hotjava html//", - "-//sun microsystems corp.//dtd hotjava strict html//", - "-//w3c//dtd html 3 1995-03-24//", - "-//w3c//dtd html 3.2 draft//", - "-//w3c//dtd html 3.2 final//", - "-//w3c//dtd html 3.2//", - "-//w3c//dtd html 3.2s draft//", - "-//w3c//dtd html 4.0 frameset//", - "-//w3c//dtd html 4.0 transitional//", - "-//w3c//dtd html experimental 19960712//", - "-//w3c//dtd html experimental 970421//", - "-//w3c//dtd w3 html//", - "-//w3o//dtd w3 html 3.0//", - "-//webtechs//dtd mozilla html 2.0//", - "-//webtechs//dtd mozilla html//")) - or publicId in - ("-//w3o//dtd w3 html strict 3.0//en//", - "-/w3c/dtd html 4.0 transitional/en", - "html") - or publicId.startswith( - ("-//w3c//dtd html 4.01 frameset//", - "-//w3c//dtd html 4.01 transitional//")) and - systemId is None - or systemId and systemId.lower() == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"): + if (not correct or token["name"] != "html" or + publicId.startswith( + ("+//silmaril//dtd html pro v0r11 19970101//", + "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", + "-//as//dtd html 3.0 aswedit + extensions//", + "-//ietf//dtd html 2.0 level 1//", + "-//ietf//dtd html 2.0 level 2//", + "-//ietf//dtd html 2.0 strict level 1//", + "-//ietf//dtd html 2.0 strict level 2//", + "-//ietf//dtd html 2.0 strict//", + "-//ietf//dtd html 2.0//", + "-//ietf//dtd html 2.1e//", + "-//ietf//dtd html 3.0//", + "-//ietf//dtd html 3.2 final//", + "-//ietf//dtd html 3.2//", + "-//ietf//dtd html 3//", + "-//ietf//dtd html level 0//", + "-//ietf//dtd html level 1//", + "-//ietf//dtd html level 2//", + "-//ietf//dtd html level 3//", + "-//ietf//dtd html strict level 0//", + "-//ietf//dtd html strict level 1//", + "-//ietf//dtd html strict level 2//", + "-//ietf//dtd html strict level 3//", + "-//ietf//dtd html strict//", + "-//ietf//dtd html//", + "-//metrius//dtd metrius presentational//", + "-//microsoft//dtd internet explorer 2.0 html strict//", + "-//microsoft//dtd internet explorer 2.0 html//", + "-//microsoft//dtd internet explorer 2.0 tables//", + "-//microsoft//dtd internet explorer 3.0 html strict//", + "-//microsoft//dtd internet explorer 3.0 html//", + "-//microsoft//dtd internet explorer 3.0 tables//", + "-//netscape comm. corp.//dtd html//", + "-//netscape comm. corp.//dtd strict html//", + "-//o'reilly and associates//dtd html 2.0//", + "-//o'reilly and associates//dtd html extended 1.0//", + "-//o'reilly and associates//dtd html extended relaxed 1.0//", + "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", + "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", + "-//spyglass//dtd html 2.0 extended//", + "-//sq//dtd html 2.0 hotmetal + extensions//", + "-//sun microsystems corp.//dtd hotjava html//", + "-//sun microsystems corp.//dtd hotjava strict html//", + "-//w3c//dtd html 3 1995-03-24//", + "-//w3c//dtd html 3.2 draft//", + "-//w3c//dtd html 3.2 final//", + "-//w3c//dtd html 3.2//", + "-//w3c//dtd html 3.2s draft//", + "-//w3c//dtd html 4.0 frameset//", + "-//w3c//dtd html 4.0 transitional//", + "-//w3c//dtd html experimental 19960712//", + "-//w3c//dtd html experimental 970421//", + "-//w3c//dtd w3 html//", + "-//w3o//dtd w3 html 3.0//", + "-//webtechs//dtd mozilla html 2.0//", + "-//webtechs//dtd mozilla html//")) or + publicId in ("-//w3o//dtd w3 html strict 3.0//en//", + "-/w3c/dtd html 4.0 transitional/en", + "html") or + publicId.startswith( + ("-//w3c//dtd html 4.01 frameset//", + "-//w3c//dtd html 4.01 transitional//")) and + systemId is None or + systemId and systemId.lower() == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"): self.parser.compatMode = "quirks" elif (publicId.startswith( ("-//w3c//dtd xhtml 1.0 frameset//", - "-//w3c//dtd xhtml 1.0 transitional//")) - or publicId.startswith( + "-//w3c//dtd xhtml 1.0 transitional//")) or + publicId.startswith( ("-//w3c//dtd html 4.01 frameset//", "-//w3c//dtd html 4.01 transitional//")) and systemId is not None): @@ -660,13 +590,13 @@ class BeforeHeadPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("head", self.startTagHead) ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ (("head", "body", "html", "br"), self.endTagImplyHead) ]) self.endTagHandler.default = self.endTagOther @@ -706,10 +636,11 @@ class InHeadPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("title", self.startTagTitle), - (("noscript", "noframes", "style"), self.startTagNoScriptNoFramesStyle), + (("noframes", "style"), self.startTagNoFramesStyle), + ("noscript", self.startTagNoscript), ("script", self.startTagScript), (("base", "basefont", "bgsound", "command", "link"), self.startTagBaseLinkCommand), @@ -718,7 +649,7 @@ def __init__(self, parser, tree): ]) self.startTagHandler.default = self.startTagOther - self. endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("head", self.endTagHead), (("br", "html", "body"), self.endTagHtmlBodyBr) ]) @@ -760,18 +691,25 @@ def startTagMeta(self, token): # the abstract Unicode string, and just use the # ContentAttrParser on that, but using UTF-8 allows all chars # to be encoded and as a ASCII-superset works. - data = inputstream.EncodingBytes(attributes["content"].encode("utf-8")) - parser = inputstream.ContentAttrParser(data) + data = _inputstream.EncodingBytes(attributes["content"].encode("utf-8")) + parser = _inputstream.ContentAttrParser(data) codec = parser.parse() self.parser.tokenizer.stream.changeEncoding(codec) def startTagTitle(self, token): self.parser.parseRCDataRawtext(token, "RCDATA") - def startTagNoScriptNoFramesStyle(self, token): + def startTagNoFramesStyle(self, token): # Need to decide whether to implement the scripting-disabled case self.parser.parseRCDataRawtext(token, "RAWTEXT") + def startTagNoscript(self, token): + if self.parser.scripting: + self.parser.parseRCDataRawtext(token, "RAWTEXT") + else: + self.tree.insertElement(token) + self.parser.phase = self.parser.phases["inHeadNoscript"] + def startTagScript(self, token): self.tree.insertElement(token) self.parser.tokenizer.state = self.parser.tokenizer.scriptDataState @@ -797,15 +735,75 @@ def endTagOther(self, token): def anythingElse(self): self.endTagHead(impliedTagToken("head")) - # XXX If we implement a parser for which scripting is disabled we need to - # implement this phase. - # - # class InHeadNoScriptPhase(Phase): + class InHeadNoscriptPhase(Phase): + def __init__(self, parser, tree): + Phase.__init__(self, parser, tree) + + self.startTagHandler = _utils.MethodDispatcher([ + ("html", self.startTagHtml), + (("basefont", "bgsound", "link", "meta", "noframes", "style"), self.startTagBaseLinkCommand), + (("head", "noscript"), self.startTagHeadNoscript), + ]) + self.startTagHandler.default = self.startTagOther + + self.endTagHandler = _utils.MethodDispatcher([ + ("noscript", self.endTagNoscript), + ("br", self.endTagBr), + ]) + self.endTagHandler.default = self.endTagOther + + def processEOF(self): + self.parser.parseError("eof-in-head-noscript") + self.anythingElse() + return True + + def processComment(self, token): + return self.parser.phases["inHead"].processComment(token) + + def processCharacters(self, token): + self.parser.parseError("char-in-head-noscript") + self.anythingElse() + return token + + def processSpaceCharacters(self, token): + return self.parser.phases["inHead"].processSpaceCharacters(token) + + def startTagHtml(self, token): + return self.parser.phases["inBody"].processStartTag(token) + + def startTagBaseLinkCommand(self, token): + return self.parser.phases["inHead"].processStartTag(token) + + def startTagHeadNoscript(self, token): + self.parser.parseError("unexpected-start-tag", {"name": token["name"]}) + + def startTagOther(self, token): + self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]}) + self.anythingElse() + return token + + def endTagNoscript(self, token): + node = self.parser.tree.openElements.pop() + assert node.name == "noscript", "Expected noscript got %s" % node.name + self.parser.phase = self.parser.phases["inHead"] + + def endTagBr(self, token): + self.parser.parseError("unexpected-inhead-noscript-tag", {"name": token["name"]}) + self.anythingElse() + return token + + def endTagOther(self, token): + self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) + + def anythingElse(self): + # Caller must raise parse error first! + self.endTagNoscript(impliedTagToken("noscript")) + class AfterHeadPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("body", self.startTagBody), ("frameset", self.startTagFrameset), @@ -815,8 +813,8 @@ def __init__(self, parser, tree): ("head", self.startTagHead) ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([(("body", "html", "br"), - self.endTagHtmlBodyBr)]) + self.endTagHandler = _utils.MethodDispatcher([(("body", "html", "br"), + self.endTagHtmlBodyBr)]) self.endTagHandler.default = self.endTagOther def processEOF(self): @@ -874,10 +872,10 @@ class InBodyPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - # Keep a ref to this for special handling of whitespace in <pre> - self.processSpaceCharactersNonPre = self.processSpaceCharacters + # Set this to the default handler + self.processSpaceCharacters = self.processSpaceCharactersNonPre - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), (("base", "basefont", "bgsound", "command", "link", "meta", "script", "style", "title"), @@ -885,7 +883,7 @@ def __init__(self, parser, tree): ("body", self.startTagBody), ("frameset", self.startTagFrameset), (("address", "article", "aside", "blockquote", "center", "details", - "details", "dir", "div", "dl", "fieldset", "figcaption", "figure", + "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "main", "menu", "nav", "ol", "p", "section", "summary", "ul"), self.startTagCloseP), @@ -911,7 +909,8 @@ def __init__(self, parser, tree): ("isindex", self.startTagIsIndex), ("textarea", self.startTagTextarea), ("iframe", self.startTagIFrame), - (("noembed", "noframes", "noscript"), self.startTagRawtext), + ("noscript", self.startTagNoscript), + (("noembed", "noframes"), self.startTagRawtext), ("select", self.startTagSelect), (("rp", "rt"), self.startTagRpRt), (("option", "optgroup"), self.startTagOpt), @@ -923,7 +922,7 @@ def __init__(self, parser, tree): ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("body", self.endTagBody), ("html", self.endTagHtml), (("address", "article", "aside", "blockquote", "button", "center", @@ -942,17 +941,9 @@ def __init__(self, parser, tree): self.endTagHandler.default = self.endTagOther def isMatchingFormattingElement(self, node1, node2): - if node1.name != node2.name or node1.namespace != node2.namespace: - return False - elif len(node1.attributes) != len(node2.attributes): - return False - else: - attributes1 = sorted(node1.attributes.items()) - attributes2 = sorted(node2.attributes.items()) - for attr1, attr2 in zip(attributes1, attributes2): - if attr1 != attr2: - return False - return True + return (node1.name == node2.name and + node1.namespace == node2.namespace and + node1.attributes == node2.attributes) # helper def addFormattingElement(self, token): @@ -988,8 +979,8 @@ def processSpaceCharactersDropNewline(self, token): data = token["data"] self.processSpaceCharacters = self.processSpaceCharactersNonPre if (data.startswith("\n") and - self.tree.openElements[-1].name in ("pre", "listing", "textarea") - and not self.tree.openElements[-1].hasContent()): + self.tree.openElements[-1].name in ("pre", "listing", "textarea") and + not self.tree.openElements[-1].hasContent()): data = data[1:] if data: self.tree.reconstructActiveFormattingElements() @@ -1007,7 +998,7 @@ def processCharacters(self, token): for char in token["data"]])): self.parser.framesetOK = False - def processSpaceCharacters(self, token): + def processSpaceCharactersNonPre(self, token): self.tree.reconstructActiveFormattingElements() self.tree.insertText(token["data"]) @@ -1016,8 +1007,8 @@ def startTagProcessInHead(self, token): def startTagBody(self, token): self.parser.parseError("unexpected-start-tag", {"name": "body"}) - if (len(self.tree.openElements) == 1 - or self.tree.openElements[1].name != "body"): + if (len(self.tree.openElements) == 1 or + self.tree.openElements[1].name != "body"): assert self.parser.innerHTML else: self.parser.framesetOK = False @@ -1232,6 +1223,12 @@ def startTagIFrame(self, token): self.parser.framesetOK = False self.startTagRawtext(token) + def startTagNoscript(self, token): + if self.parser.scripting: + self.startTagRawtext(token) + else: + self.startTagOther(token) + def startTagRawtext(self, token): """iframe, noembed noframes, noscript(if scripting enabled)""" self.parser.parseRCDataRawtext(token, "RAWTEXT") @@ -1327,7 +1324,7 @@ def endTagBody(self, token): # Not sure this is the correct name for the parse error self.parser.parseError( "expected-one-end-tag-but-got-another", - {"expectedName": "body", "gotName": node.name}) + {"gotName": "body", "expectedName": node.name}) break self.parser.phase = self.parser.phases["afterBody"] @@ -1595,9 +1592,9 @@ def endTagOther(self, token): class TextPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([]) + self.startTagHandler = _utils.MethodDispatcher([]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("script", self.endTagScript)]) self.endTagHandler.default = self.endTagOther @@ -1629,7 +1626,7 @@ class InTablePhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-table def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("caption", self.startTagCaption), ("colgroup", self.startTagColgroup), @@ -1643,7 +1640,7 @@ def __init__(self, parser, tree): ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("table", self.endTagTable), (("body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"), self.endTagIgnore) @@ -1820,14 +1817,14 @@ class InCaptionPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), (("caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"), self.startTagTableElement) ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("caption", self.endTagCaption), ("table", self.endTagTable), (("body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", @@ -1892,13 +1889,13 @@ class InColumnGroupPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("col", self.startTagCol) ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("colgroup", self.endTagColgroup), ("col", self.endTagCol) ]) @@ -1926,6 +1923,7 @@ def processCharacters(self, token): def startTagCol(self, token): self.tree.insertElement(token) self.tree.openElements.pop() + token["selfClosingAcknowledged"] = True def startTagOther(self, token): ignoreEndTag = self.ignoreEndTagColgroup() @@ -1955,7 +1953,7 @@ class InTableBodyPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-table0 def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("tr", self.startTagTr), (("td", "th"), self.startTagTableCell), @@ -1964,7 +1962,7 @@ def __init__(self, parser, tree): ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ (("tbody", "tfoot", "thead"), self.endTagTableRowGroup), ("table", self.endTagTable), (("body", "caption", "col", "colgroup", "html", "td", "th", @@ -2053,7 +2051,7 @@ class InRowPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-row def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), (("td", "th"), self.startTagTableCell), (("caption", "col", "colgroup", "tbody", "tfoot", "thead", @@ -2061,7 +2059,7 @@ def __init__(self, parser, tree): ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("tr", self.endTagTr), ("table", self.endTagTable), (("tbody", "tfoot", "thead"), self.endTagTableRowGroup), @@ -2142,14 +2140,14 @@ class InCellPhase(Phase): # http://www.whatwg.org/specs/web-apps/current-work/#in-cell def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), (("caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"), self.startTagTableOther) ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ (("td", "th"), self.endTagTableCell), (("body", "caption", "col", "colgroup", "html"), self.endTagIgnore), (("table", "tbody", "tfoot", "thead", "tr"), self.endTagImply) @@ -2218,7 +2216,7 @@ class InSelectPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("option", self.startTagOption), ("optgroup", self.startTagOptgroup), @@ -2228,7 +2226,7 @@ def __init__(self, parser, tree): ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("option", self.endTagOption), ("optgroup", self.endTagOptgroup), ("select", self.endTagSelect) @@ -2318,13 +2316,13 @@ class InSelectInTablePhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ (("caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"), self.startTagTable) ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ (("caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th"), self.endTagTable) ]) @@ -2445,7 +2443,7 @@ def processStartTag(self, token): def processEndTag(self, token): nodeIndex = len(self.tree.openElements) - 1 node = self.tree.openElements[-1] - if node.name != token["name"]: + if node.name.translate(asciiUpper2Lower) != token["name"]: self.parser.parseError("unexpected-end-tag", {"name": token["name"]}) while True: @@ -2472,12 +2470,12 @@ class AfterBodyPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml) ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([("html", self.endTagHtml)]) + self.endTagHandler = _utils.MethodDispatcher([("html", self.endTagHtml)]) self.endTagHandler.default = self.endTagOther def processEOF(self): @@ -2520,7 +2518,7 @@ class InFramesetPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("frameset", self.startTagFrameset), ("frame", self.startTagFrame), @@ -2528,7 +2526,7 @@ def __init__(self, parser, tree): ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("frameset", self.endTagFrameset) ]) self.endTagHandler.default = self.endTagOther @@ -2564,7 +2562,7 @@ def endTagFrameset(self, token): self.tree.openElements.pop() if (not self.parser.innerHTML and self.tree.openElements[-1].name != "frameset"): - # If we're not in innerHTML mode and the the current node is not a + # If we're not in innerHTML mode and the current node is not a # "frameset" element (anymore) then switch. self.parser.phase = self.parser.phases["afterFrameset"] @@ -2577,13 +2575,13 @@ class AfterFramesetPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("noframes", self.startTagNoframes) ]) self.startTagHandler.default = self.startTagOther - self.endTagHandler = utils.MethodDispatcher([ + self.endTagHandler = _utils.MethodDispatcher([ ("html", self.endTagHtml) ]) self.endTagHandler.default = self.endTagOther @@ -2613,7 +2611,7 @@ class AfterAfterBodyPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml) ]) self.startTagHandler.default = self.startTagOther @@ -2651,7 +2649,7 @@ class AfterAfterFramesetPhase(Phase): def __init__(self, parser, tree): Phase.__init__(self, parser, tree) - self.startTagHandler = utils.MethodDispatcher([ + self.startTagHandler = _utils.MethodDispatcher([ ("html", self.startTagHtml), ("noframes", self.startTagNoFrames) ]) @@ -2682,13 +2680,14 @@ def startTagOther(self, token): def processEndTag(self, token): self.parser.parseError("expected-eof-but-got-end-tag", {"name": token["name"]}) + # pylint:enable=unused-argument return { "initial": InitialPhase, "beforeHtml": BeforeHtmlPhase, "beforeHead": BeforeHeadPhase, "inHead": InHeadPhase, - # XXX "inHeadNoscript": InHeadNoScriptPhase, + "inHeadNoscript": InHeadNoscriptPhase, "afterHead": AfterHeadPhase, "inBody": InBodyPhase, "text": TextPhase, @@ -2711,6 +2710,16 @@ def processEndTag(self, token): } +def adjust_attributes(token, replacements): + if PY3 or _utils.PY27: + needs_adjustment = viewkeys(token['data']) & viewkeys(replacements) + else: + needs_adjustment = frozenset(token['data']) & frozenset(replacements) + if needs_adjustment: + token['data'] = OrderedDict((replacements.get(k, k), v) + for k, v in token['data'].items()) + + def impliedTagToken(name, type="EndTag", attributes=None, selfClosing=False): if attributes is None: diff --git a/pip/_vendor/html5lib/sanitizer.py b/pip/_vendor/html5lib/sanitizer.py deleted file mode 100644 --- a/pip/_vendor/html5lib/sanitizer.py +++ /dev/null @@ -1,300 +0,0 @@ -from __future__ import absolute_import, division, unicode_literals - -import re -from xml.sax.saxutils import escape, unescape -from six.moves import urllib_parse as urlparse - -from .tokenizer import HTMLTokenizer -from .constants import tokenTypes - - -content_type_rgx = re.compile(r''' - ^ - # Match a content type <application>/<type> - (?P<content_type>[-a-zA-Z0-9.]+/[-a-zA-Z0-9.]+) - # Match any character set and encoding - (?:(?:;charset=(?:[-a-zA-Z0-9]+)(?:;(?:base64))?) - |(?:;(?:base64))?(?:;charset=(?:[-a-zA-Z0-9]+))?) - # Assume the rest is data - ,.* - $ - ''', - re.VERBOSE) - - -class HTMLSanitizerMixin(object): - """ sanitization of XHTML+MathML+SVG and of inline style attributes.""" - - acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', - 'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button', - 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', - 'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', - 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset', - 'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1', - 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins', - 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter', - 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option', - 'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select', - 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong', - 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot', - 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video'] - - mathml_elements = ['maction', 'math', 'merror', 'mfrac', 'mi', - 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', - 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub', - 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', - 'munderover', 'none'] - - svg_elements = ['a', 'animate', 'animateColor', 'animateMotion', - 'animateTransform', 'clipPath', 'circle', 'defs', 'desc', 'ellipse', - 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern', - 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', - 'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect', - 'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use'] - - acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey', - 'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis', - 'background', 'balance', 'bgcolor', 'bgproperties', 'border', - 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding', - 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff', - 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', - 'cols', 'colspan', 'compact', 'contenteditable', 'controls', 'coords', - 'data', 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default', - 'delay', 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end', - 'face', 'for', 'form', 'frame', 'galleryimg', 'gutter', 'headers', - 'height', 'hidefocus', 'hidden', 'high', 'href', 'hreflang', 'hspace', - 'icon', 'id', 'inputmode', 'ismap', 'keytype', 'label', 'leftspacing', - 'lang', 'list', 'longdesc', 'loop', 'loopcount', 'loopend', - 'loopstart', 'low', 'lowsrc', 'max', 'maxlength', 'media', 'method', - 'min', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'open', - 'optimum', 'pattern', 'ping', 'point-size', 'poster', 'pqg', 'preload', - 'prompt', 'radiogroup', 'readonly', 'rel', 'repeat-max', 'repeat-min', - 'replace', 'required', 'rev', 'rightspacing', 'rows', 'rowspan', - 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start', - 'step', 'style', 'summary', 'suppress', 'tabindex', 'target', - 'template', 'title', 'toppadding', 'type', 'unselectable', 'usemap', - 'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml', - 'width', 'wrap', 'xml:lang'] - - mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign', - 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth', - 'display', 'displaystyle', 'equalcolumns', 'equalrows', 'fence', - 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace', - 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize', - 'minsize', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines', - 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection', - 'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show', - 'xlink:type', 'xmlns', 'xmlns:xlink'] - - svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic', - 'arabic-form', 'ascent', 'attributeName', 'attributeType', - 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height', - 'class', 'clip-path', 'color', 'color-rendering', 'content', 'cx', - 'cy', 'd', 'dx', 'dy', 'descent', 'display', 'dur', 'end', 'fill', - 'fill-opacity', 'fill-rule', 'font-family', 'font-size', - 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from', - 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'hanging', - 'height', 'horiz-adv-x', 'horiz-origin-x', 'id', 'ideographic', 'k', - 'keyPoints', 'keySplines', 'keyTimes', 'lang', 'marker-end', - 'marker-mid', 'marker-start', 'markerHeight', 'markerUnits', - 'markerWidth', 'mathematical', 'max', 'min', 'name', 'offset', - 'opacity', 'orient', 'origin', 'overline-position', - 'overline-thickness', 'panose-1', 'path', 'pathLength', 'points', - 'preserveAspectRatio', 'r', 'refX', 'refY', 'repeatCount', - 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', - 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color', - 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', - 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', - 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', - 'stroke-width', 'systemLanguage', 'target', 'text-anchor', 'to', - 'transform', 'type', 'u1', 'u2', 'underline-position', - 'underline-thickness', 'unicode', 'unicode-range', 'units-per-em', - 'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x', - 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole', - 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', - 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', - 'y1', 'y2', 'zoomAndPan'] - - attr_val_is_uri = ['href', 'src', 'cite', 'action', 'longdesc', 'poster', 'background', 'datasrc', - 'dynsrc', 'lowsrc', 'ping', 'poster', 'xlink:href', 'xml:base'] - - svg_attr_val_allows_ref = ['clip-path', 'color-profile', 'cursor', 'fill', - 'filter', 'marker', 'marker-start', 'marker-mid', 'marker-end', - 'mask', 'stroke'] - - svg_allow_local_href = ['altGlyph', 'animate', 'animateColor', - 'animateMotion', 'animateTransform', 'cursor', 'feImage', 'filter', - 'linearGradient', 'pattern', 'radialGradient', 'textpath', 'tref', - 'set', 'use'] - - acceptable_css_properties = ['azimuth', 'background-color', - 'border-bottom-color', 'border-collapse', 'border-color', - 'border-left-color', 'border-right-color', 'border-top-color', 'clear', - 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font', - 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', - 'height', 'letter-spacing', 'line-height', 'overflow', 'pause', - 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness', - 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation', - 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent', - 'unicode-bidi', 'vertical-align', 'voice-family', 'volume', - 'white-space', 'width'] - - acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue', - 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', - 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left', - 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive', - 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top', - 'transparent', 'underline', 'white', 'yellow'] - - acceptable_svg_properties = ['fill', 'fill-opacity', 'fill-rule', - 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', - 'stroke-opacity'] - - acceptable_protocols = ['ed2k', 'ftp', 'http', 'https', 'irc', - 'mailto', 'news', 'gopher', 'nntp', 'telnet', 'webcal', - 'xmpp', 'callto', 'feed', 'urn', 'aim', 'rsync', 'tag', - 'ssh', 'sftp', 'rtsp', 'afs', 'data'] - - acceptable_content_types = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp', 'text/plain'] - - # subclasses may define their own versions of these constants - allowed_elements = acceptable_elements + mathml_elements + svg_elements - allowed_attributes = acceptable_attributes + mathml_attributes + svg_attributes - allowed_css_properties = acceptable_css_properties - allowed_css_keywords = acceptable_css_keywords - allowed_svg_properties = acceptable_svg_properties - allowed_protocols = acceptable_protocols - allowed_content_types = acceptable_content_types - - # Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and - # stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style - # attributes are parsed, and a restricted set, # specified by - # ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through. - # attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified - # in ALLOWED_PROTOCOLS are allowed. - # - # sanitize_html('<script> do_nasty_stuff() </script>') - # => &lt;script> do_nasty_stuff() &lt;/script> - # sanitize_html('<a href="javascript: sucker();">Click here for $100</a>') - # => <a>Click here for $100</a> - def sanitize_token(self, token): - - # accommodate filters which use token_type differently - token_type = token["type"] - if token_type in list(tokenTypes.keys()): - token_type = tokenTypes[token_type] - - if token_type in (tokenTypes["StartTag"], tokenTypes["EndTag"], - tokenTypes["EmptyTag"]): - if token["name"] in self.allowed_elements: - return self.allowed_token(token, token_type) - else: - return self.disallowed_token(token, token_type) - elif token_type == tokenTypes["Comment"]: - pass - else: - return token - - def allowed_token(self, token, token_type): - if "data" in token: - attrs = dict([(name, val) for name, val in - token["data"][::-1] - if name in self.allowed_attributes]) - for attr in self.attr_val_is_uri: - if attr not in attrs: - continue - val_unescaped = re.sub("[`\000-\040\177-\240\s]+", '', - unescape(attrs[attr])).lower() - # remove replacement characters from unescaped characters - val_unescaped = val_unescaped.replace("\ufffd", "") - try: - uri = urlparse.urlparse(val_unescaped) - except ValueError: - uri = None - del attrs[attr] - if uri and uri.scheme: - if uri.scheme not in self.allowed_protocols: - del attrs[attr] - if uri.scheme == 'data': - m = content_type_rgx.match(uri.path) - if not m: - del attrs[attr] - elif m.group('content_type') not in self.allowed_content_types: - del attrs[attr] - - for attr in self.svg_attr_val_allows_ref: - if attr in attrs: - attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)', - ' ', - unescape(attrs[attr])) - if (token["name"] in self.svg_allow_local_href and - 'xlink:href' in attrs and re.search('^\s*[^#\s].*', - attrs['xlink:href'])): - del attrs['xlink:href'] - if 'style' in attrs: - attrs['style'] = self.sanitize_css(attrs['style']) - token["data"] = [[name, val] for name, val in list(attrs.items())] - return token - - def disallowed_token(self, token, token_type): - if token_type == tokenTypes["EndTag"]: - token["data"] = "</%s>" % token["name"] - elif token["data"]: - attrs = ''.join([' %s="%s"' % (k, escape(v)) for k, v in token["data"]]) - token["data"] = "<%s%s>" % (token["name"], attrs) - else: - token["data"] = "<%s>" % token["name"] - if token.get("selfClosing"): - token["data"] = token["data"][:-1] + "/>" - - if token["type"] in list(tokenTypes.keys()): - token["type"] = "Characters" - else: - token["type"] = tokenTypes["Characters"] - - del token["name"] - return token - - def sanitize_css(self, style): - # disallow urls - style = re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ', style) - - # gauntlet - if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): - return '' - if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): - return '' - - clean = [] - for prop, value in re.findall("([-\w]+)\s*:\s*([^:;]*)", style): - if not value: - continue - if prop.lower() in self.allowed_css_properties: - clean.append(prop + ': ' + value + ';') - elif prop.split('-')[0].lower() in ['background', 'border', 'margin', - 'padding']: - for keyword in value.split(): - if keyword not in self.acceptable_css_keywords and \ - not re.match("^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$", keyword): - break - else: - clean.append(prop + ': ' + value + ';') - elif prop.lower() in self.allowed_svg_properties: - clean.append(prop + ': ' + value + ';') - - return ' '.join(clean) - - -class HTMLSanitizer(HTMLTokenizer, HTMLSanitizerMixin): - def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True, - lowercaseElementName=False, lowercaseAttrName=False, parser=None): - # Change case matching defaults as we only output lowercase html anyway - # This solution doesn't seem ideal... - HTMLTokenizer.__init__(self, stream, encoding, parseMeta, useChardet, - lowercaseElementName, lowercaseAttrName, parser=parser) - - def __iter__(self): - for token in HTMLTokenizer.__iter__(self): - token = self.sanitize_token(token) - if token: - yield token diff --git a/pip/_vendor/html5lib/serializer/htmlserializer.py b/pip/_vendor/html5lib/serializer.py similarity index 68% rename from pip/_vendor/html5lib/serializer/htmlserializer.py rename to pip/_vendor/html5lib/serializer.py --- a/pip/_vendor/html5lib/serializer/htmlserializer.py +++ b/pip/_vendor/html5lib/serializer.py @@ -1,79 +1,87 @@ from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type -try: - from functools import reduce -except ImportError: - pass +import re + +from codecs import register_error, xmlcharrefreplace_errors -from ..constants import voidElements, booleanAttributes, spaceCharacters -from ..constants import rcdataElements, entities, xmlEntities -from .. import utils +from .constants import voidElements, booleanAttributes, spaceCharacters +from .constants import rcdataElements, entities, xmlEntities +from . import treewalkers, _utils from xml.sax.saxutils import escape -spaceCharacters = "".join(spaceCharacters) - -try: - from codecs import register_error, xmlcharrefreplace_errors -except ImportError: - unicode_encode_errors = "strict" -else: - unicode_encode_errors = "htmlentityreplace" - - encode_entity_map = {} - is_ucs4 = len("\U0010FFFF") == 1 - for k, v in list(entities.items()): - # skip multi-character entities - if ((is_ucs4 and len(v) > 1) or - (not is_ucs4 and len(v) > 2)): - continue - if v != "&": - if len(v) == 2: - v = utils.surrogatePairToCodepoint(v) - else: - v = ord(v) - if v not in encode_entity_map or k.islower(): - # prefer &lt; over &LT; and similarly for &amp;, &gt;, etc. - encode_entity_map[v] = k - - def htmlentityreplace_errors(exc): - if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): - res = [] - codepoints = [] - skip = False - for i, c in enumerate(exc.object[exc.start:exc.end]): - if skip: - skip = False - continue - index = i + exc.start - if utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]): - codepoint = utils.surrogatePairToCodepoint(exc.object[index:index + 2]) - skip = True - else: - codepoint = ord(c) - codepoints.append(codepoint) - for cp in codepoints: - e = encode_entity_map.get(cp) - if e: - res.append("&") - res.append(e) - if not e.endswith(";"): - res.append(";") - else: - res.append("&#x%s;" % (hex(cp)[2:])) - return ("".join(res), exc.end) +_quoteAttributeSpecChars = "".join(spaceCharacters) + "\"'=<>`" +_quoteAttributeSpec = re.compile("[" + _quoteAttributeSpecChars + "]") +_quoteAttributeLegacy = re.compile("[" + _quoteAttributeSpecChars + + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n" + "\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15" + "\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" + "\x20\x2f\x60\xa0\u1680\u180e\u180f\u2000" + "\u2001\u2002\u2003\u2004\u2005\u2006\u2007" + "\u2008\u2009\u200a\u2028\u2029\u202f\u205f" + "\u3000]") + + +_encode_entity_map = {} +_is_ucs4 = len("\U0010FFFF") == 1 +for k, v in list(entities.items()): + # skip multi-character entities + if ((_is_ucs4 and len(v) > 1) or + (not _is_ucs4 and len(v) > 2)): + continue + if v != "&": + if len(v) == 2: + v = _utils.surrogatePairToCodepoint(v) else: - return xmlcharrefreplace_errors(exc) + v = ord(v) + if v not in _encode_entity_map or k.islower(): + # prefer &lt; over &LT; and similarly for &amp;, &gt;, etc. + _encode_entity_map[v] = k + + +def htmlentityreplace_errors(exc): + if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): + res = [] + codepoints = [] + skip = False + for i, c in enumerate(exc.object[exc.start:exc.end]): + if skip: + skip = False + continue + index = i + exc.start + if _utils.isSurrogatePair(exc.object[index:min([exc.end, index + 2])]): + codepoint = _utils.surrogatePairToCodepoint(exc.object[index:index + 2]) + skip = True + else: + codepoint = ord(c) + codepoints.append(codepoint) + for cp in codepoints: + e = _encode_entity_map.get(cp) + if e: + res.append("&") + res.append(e) + if not e.endswith(";"): + res.append(";") + else: + res.append("&#x%s;" % (hex(cp)[2:])) + return ("".join(res), exc.end) + else: + return xmlcharrefreplace_errors(exc) + +register_error("htmlentityreplace", htmlentityreplace_errors) - register_error(unicode_encode_errors, htmlentityreplace_errors) - del register_error +def serialize(input, tree="etree", encoding=None, **serializer_opts): + # XXX: Should we cache this? + walker = treewalkers.getTreeWalker(tree) + s = HTMLSerializer(**serializer_opts) + return s.render(walker(input), encoding) class HTMLSerializer(object): # attribute quoting options - quote_attr_values = False + quote_attr_values = "legacy" # be secure by default quote_char = '"' use_best_quote_char = True @@ -109,9 +117,9 @@ def __init__(self, **kwargs): inject_meta_charset=True|False Whether it insert a meta element to define the character set of the document. - quote_attr_values=True|False + quote_attr_values="legacy"|"spec"|"always" Whether to quote attribute values that don't require quoting - per HTML5 parsing rules. + per legacy browser behaviour, when required by the standard, or always. quote_char=u'"'|u"'" Use given quote character for attribute quoting. Default is to use double quote unless attribute value contains a double quote, @@ -147,6 +155,9 @@ def __init__(self, **kwargs): .. _html5lib user documentation: http://code.google.com/p/html5lib/wiki/UserDocumentation """ + unexpected_args = frozenset(kwargs) - frozenset(self.options) + if len(unexpected_args) > 0: + raise TypeError("__init__() got an unexpected keyword argument '%s'" % next(iter(unexpected_args))) if 'quote_char' in kwargs: self.use_best_quote_char = False for attr in self.options: @@ -157,7 +168,7 @@ def __init__(self, **kwargs): def encode(self, string): assert(isinstance(string, text_type)) if self.encoding: - return string.encode(self.encoding, unicode_encode_errors) + return string.encode(self.encoding, "htmlentityreplace") else: return string @@ -169,28 +180,30 @@ def encodeStrict(self, string): return string def serialize(self, treewalker, encoding=None): + # pylint:disable=too-many-nested-blocks self.encoding = encoding in_cdata = False self.errors = [] if encoding and self.inject_meta_charset: - from ..filters.inject_meta_charset import Filter + from .filters.inject_meta_charset import Filter treewalker = Filter(treewalker, encoding) + # Alphabetical attributes is here under the assumption that none of + # the later filters add or change order of attributes; it needs to be + # before the sanitizer so escaped elements come out correctly + if self.alphabetical_attributes: + from .filters.alphabeticalattributes import Filter + treewalker = Filter(treewalker) # WhitespaceFilter should be used before OptionalTagFilter # for maximum efficiently of this latter filter if self.strip_whitespace: - from ..filters.whitespace import Filter + from .filters.whitespace import Filter treewalker = Filter(treewalker) if self.sanitize: - from ..filters.sanitizer import Filter + from .filters.sanitizer import Filter treewalker = Filter(treewalker) if self.omit_optional_tags: - from ..filters.optionaltags import Filter - treewalker = Filter(treewalker) - # Alphabetical attributes must be last, as other filters - # could add attributes and alter the order - if self.alphabetical_attributes: - from ..filters.alphabeticalattributes import Filter + from .filters.optionaltags import Filter treewalker = Filter(treewalker) for token in treewalker: @@ -229,7 +242,7 @@ def serialize(self, treewalker, encoding=None): 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_name), attr_value in token["data"].items(): # TODO: Add namespace support here k = attr_name v = attr_value @@ -237,14 +250,18 @@ def serialize(self, treewalker, encoding=None): yield self.encodeStrict(k) if not self.minimize_boolean_attributes or \ - (k not in booleanAttributes.get(name, tuple()) - and k not in booleanAttributes.get("", tuple())): + (k not in booleanAttributes.get(name, tuple()) and + k not in booleanAttributes.get("", tuple())): yield self.encodeStrict("=") - if self.quote_attr_values or not v: + if self.quote_attr_values == "always" or len(v) == 0: quote_attr = True + elif self.quote_attr_values == "spec": + quote_attr = _quoteAttributeSpec.search(v) is not None + elif self.quote_attr_values == "legacy": + quote_attr = _quoteAttributeLegacy.search(v) is not None else: - quote_attr = reduce(lambda x, y: x or (y in v), - spaceCharacters + ">\"'=", False) + raise ValueError("quote_attr_values must be one of: " + "'always', 'spec', or 'legacy'") v = v.replace("&", "&amp;") if self.escape_lt_in_attrs: v = v.replace("<", "&lt;") @@ -312,6 +329,6 @@ def serializeError(self, data="XXX ERROR MESSAGE NEEDED"): raise SerializeError -def SerializeError(Exception): +class SerializeError(Exception): """Error in serialized tree""" pass diff --git a/pip/_vendor/html5lib/serializer/__init__.py b/pip/_vendor/html5lib/serializer/__init__.py deleted file mode 100644 --- a/pip/_vendor/html5lib/serializer/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -from __future__ import absolute_import, division, unicode_literals - -from .. import treewalkers - -from .htmlserializer import HTMLSerializer - - -def serialize(input, tree="etree", format="html", encoding=None, - **serializer_opts): - # XXX: Should we cache this? - walker = treewalkers.getTreeWalker(tree) - if format == "html": - s = HTMLSerializer(**serializer_opts) - else: - raise ValueError("type must be html") - return s.render(walker(input), encoding) diff --git a/pip/_vendor/html5lib/treeadapters/__init__.py b/pip/_vendor/html5lib/treeadapters/__init__.py --- a/pip/_vendor/html5lib/treeadapters/__init__.py +++ b/pip/_vendor/html5lib/treeadapters/__init__.py @@ -0,0 +1,12 @@ +from __future__ import absolute_import, division, unicode_literals + +from . import sax + +__all__ = ["sax"] + +try: + from . import genshi # noqa +except ImportError: + pass +else: + __all__.append("genshi") diff --git a/pip/_vendor/html5lib/treeadapters/genshi.py b/pip/_vendor/html5lib/treeadapters/genshi.py new file mode 100644 --- /dev/null +++ b/pip/_vendor/html5lib/treeadapters/genshi.py @@ -0,0 +1,47 @@ +from __future__ import absolute_import, division, unicode_literals + +from genshi.core import QName, Attrs +from genshi.core import START, END, TEXT, COMMENT, DOCTYPE + + +def to_genshi(walker): + text = [] + for token in walker: + type = token["type"] + if type in ("Characters", "SpaceCharacters"): + text.append(token["data"]) + elif text: + yield TEXT, "".join(text), (None, -1, -1) + text = [] + + if type in ("StartTag", "EmptyTag"): + if token["namespace"]: + name = "{%s}%s" % (token["namespace"], token["name"]) + else: + name = token["name"] + attrs = Attrs([(QName("{%s}%s" % attr if attr[0] is not None else attr[1]), value) + for attr, value in token["data"].items()]) + yield (START, (QName(name), attrs), (None, -1, -1)) + if type == "EmptyTag": + type = "EndTag" + + if type == "EndTag": + if token["namespace"]: + name = "{%s}%s" % (token["namespace"], token["name"]) + else: + name = token["name"] + + yield END, QName(name), (None, -1, -1) + + elif type == "Comment": + yield COMMENT, token["data"], (None, -1, -1) + + elif type == "Doctype": + yield DOCTYPE, (token["name"], token["publicId"], + token["systemId"]), (None, -1, -1) + + else: + pass # FIXME: What to do? + + if text: + yield TEXT, "".join(text), (None, -1, -1) diff --git a/pip/_vendor/html5lib/treebuilders/__init__.py b/pip/_vendor/html5lib/treebuilders/__init__.py --- a/pip/_vendor/html5lib/treebuilders/__init__.py +++ b/pip/_vendor/html5lib/treebuilders/__init__.py @@ -28,7 +28,7 @@ from __future__ import absolute_import, division, unicode_literals -from ..utils import default_etree +from .._utils import default_etree treeBuilderCache = {} diff --git a/pip/_vendor/html5lib/treebuilders/_base.py b/pip/_vendor/html5lib/treebuilders/base.py similarity index 97% rename from pip/_vendor/html5lib/treebuilders/_base.py rename to pip/_vendor/html5lib/treebuilders/base.py --- a/pip/_vendor/html5lib/treebuilders/_base.py +++ b/pip/_vendor/html5lib/treebuilders/base.py @@ -126,6 +126,7 @@ class TreeBuilder(object): commentClass - the class to use for comments doctypeClass - the class to use for doctypes """ + # pylint:disable=not-callable # Document class documentClass = None @@ -166,12 +167,17 @@ def elementInScope(self, target, variant=None): # If we pass a node in we match that. if we pass a string # match any node with that name exactNode = hasattr(target, "nameTuple") + if not exactNode: + if isinstance(target, text_type): + target = (namespaces["html"], target) + assert isinstance(target, tuple) listElements, invert = listElementsMap[variant] for node in reversed(self.openElements): - if (node.name == target and not exactNode or - node == target and exactNode): + if exactNode and node == target: + return True + elif not exactNode and node.nameTuple == target: return True elif (invert ^ (node.nameTuple in listElements)): return False @@ -353,8 +359,8 @@ def getTableMisnestedNodePosition(self): def generateImpliedEndTags(self, exclude=None): name = self.openElements[-1].name # XXX td, th and tr are not actually needed - if (name in frozenset(("dd", "dt", "li", "option", "optgroup", "p", "rp", "rt")) - and name != exclude): + if (name in frozenset(("dd", "dt", "li", "option", "optgroup", "p", "rp", "rt")) and + name != exclude): self.openElements.pop() # XXX This is not entirely what the specification says. We should # investigate it more closely. diff --git a/pip/_vendor/html5lib/treebuilders/dom.py b/pip/_vendor/html5lib/treebuilders/dom.py --- a/pip/_vendor/html5lib/treebuilders/dom.py +++ b/pip/_vendor/html5lib/treebuilders/dom.py @@ -1,54 +1,62 @@ from __future__ import absolute_import, division, unicode_literals +from collections import MutableMapping from xml.dom import minidom, Node import weakref -from . import _base +from . import base from .. import constants from ..constants import namespaces -from ..utils import moduleFactoryFactory +from .._utils import moduleFactoryFactory def getDomBuilder(DomImplementation): Dom = DomImplementation - class AttrList(object): + class AttrList(MutableMapping): def __init__(self, element): self.element = element def __iter__(self): - return list(self.element.attributes.items()).__iter__() + return iter(self.element.attributes.keys()) def __setitem__(self, name, value): - self.element.setAttribute(name, value) + if isinstance(name, tuple): + raise NotImplementedError + else: + attr = self.element.ownerDocument.createAttribute(name) + attr.value = value + self.element.attributes[name] = attr def __len__(self): - return len(list(self.element.attributes.items())) + return len(self.element.attributes) def items(self): - return [(item[0], item[1]) for item in - list(self.element.attributes.items())] + return list(self.element.attributes.items()) - def keys(self): - return list(self.element.attributes.keys()) + def values(self): + return list(self.element.attributes.values()) def __getitem__(self, name): - return self.element.getAttribute(name) + if isinstance(name, tuple): + raise NotImplementedError + else: + return self.element.attributes[name].value - def __contains__(self, name): + def __delitem__(self, name): if isinstance(name, tuple): raise NotImplementedError else: - return self.element.hasAttribute(name) + del self.element.attributes[name] - class NodeBuilder(_base.Node): + class NodeBuilder(base.Node): def __init__(self, element): - _base.Node.__init__(self, element.nodeName) + base.Node.__init__(self, element.nodeName) self.element = element - namespace = property(lambda self: hasattr(self.element, "namespaceURI") - and self.element.namespaceURI or None) + namespace = property(lambda self: hasattr(self.element, "namespaceURI") and + self.element.namespaceURI or None) def appendChild(self, node): node.parent = self @@ -109,7 +117,7 @@ def getNameTuple(self): nameTuple = property(getNameTuple) - class TreeBuilder(_base.TreeBuilder): + class TreeBuilder(base.TreeBuilder): # pylint:disable=unused-variable def documentClass(self): self.dom = Dom.getDOMImplementation().createDocument(None, None, None) return weakref.proxy(self) @@ -149,15 +157,16 @@ def getDocument(self): return self.dom def getFragment(self): - return _base.TreeBuilder.getFragment(self).element + return base.TreeBuilder.getFragment(self).element def insertText(self, data, parent=None): data = data if parent != self: - _base.TreeBuilder.insertText(self, data, parent) + base.TreeBuilder.insertText(self, data, parent) else: # HACK: allow text nodes as children of the document node if hasattr(self.dom, '_child_node_types'): + # pylint:disable=protected-access if Node.TEXT_NODE not in self.dom._child_node_types: self.dom._child_node_types = list(self.dom._child_node_types) self.dom._child_node_types.append(Node.TEXT_NODE) diff --git a/pip/_vendor/html5lib/treebuilders/etree.py b/pip/_vendor/html5lib/treebuilders/etree.py --- a/pip/_vendor/html5lib/treebuilders/etree.py +++ b/pip/_vendor/html5lib/treebuilders/etree.py @@ -1,13 +1,15 @@ from __future__ import absolute_import, division, unicode_literals +# pylint:disable=protected-access + from pip._vendor.six import text_type import re -from . import _base -from .. import ihatexml +from . import base +from .. import _ihatexml from .. import constants from ..constants import namespaces -from ..utils import moduleFactoryFactory +from .._utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") @@ -16,7 +18,7 @@ def getETreeBuilder(ElementTreeImplementation, fullTree=False): ElementTree = ElementTreeImplementation ElementTreeCommentType = ElementTree.Comment("asd").tag - class Element(_base.Node): + class Element(base.Node): def __init__(self, name, namespace=None): self._name = name self._namespace = namespace @@ -98,6 +100,7 @@ def insertBefore(self, node, refNode): node.parent = self def removeChild(self, node): + self._childNodes.remove(node) self._element.remove(node._element) node.parent = None @@ -139,7 +142,7 @@ def reparentChildren(self, newParent): if self._element.text is not None: newParent._element.text += self._element.text self._element.text = "" - _base.Node.reparentChildren(self, newParent) + base.Node.reparentChildren(self, newParent) class Comment(Element): def __init__(self, data): @@ -253,10 +256,10 @@ def serializeElement(element, indent=0): return "\n".join(rv) - def tostring(element): + def tostring(element): # pylint:disable=unused-variable """Serialize an element and its child nodes to a string""" rv = [] - filter = ihatexml.InfosetFilter() + filter = _ihatexml.InfosetFilter() def serializeElement(element): if isinstance(element, ElementTree.ElementTree): @@ -307,7 +310,7 @@ def serializeElement(element): return "".join(rv) - class TreeBuilder(_base.TreeBuilder): + class TreeBuilder(base.TreeBuilder): # pylint:disable=unused-variable documentClass = Document doctypeClass = DocumentType elementClass = Element @@ -329,7 +332,7 @@ def getDocument(self): return self.document._element.find("html") def getFragment(self): - return _base.TreeBuilder.getFragment(self)._element + return base.TreeBuilder.getFragment(self)._element return locals() diff --git a/pip/_vendor/html5lib/treebuilders/etree_lxml.py b/pip/_vendor/html5lib/treebuilders/etree_lxml.py --- a/pip/_vendor/html5lib/treebuilders/etree_lxml.py +++ b/pip/_vendor/html5lib/treebuilders/etree_lxml.py @@ -10,16 +10,17 @@ """ from __future__ import absolute_import, division, unicode_literals +# pylint:disable=protected-access import warnings import re import sys -from . import _base +from . import base from ..constants import DataLossWarning from .. import constants from . import etree as etree_builders -from .. import ihatexml +from .. import _ihatexml import lxml.etree as etree @@ -53,8 +54,7 @@ def _getChildNodes(self): def testSerializer(element): rv = [] - finalText = None - infosetFilter = ihatexml.InfosetFilter() + infosetFilter = _ihatexml.InfosetFilter(preventDoubleDashComments=True) def serializeElement(element, indent=0): if not hasattr(element, "tag"): @@ -79,7 +79,7 @@ def serializeElement(element, indent=0): next_element = next_element.getnext() elif isinstance(element, str) or isinstance(element, bytes): # Text in a fragment - assert isinstance(element, str) or sys.version_info.major == 2 + assert isinstance(element, str) or sys.version_info[0] == 2 rv.append("|%s\"%s\"" % (' ' * indent, element)) else: # Fragment case @@ -128,16 +128,12 @@ def serializeElement(element, indent=0): rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail)) serializeElement(element, 0) - if finalText is not None: - rv.append("|%s\"%s\"" % (' ' * 2, finalText)) - return "\n".join(rv) def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] - finalText = None def serializeElement(element): if not hasattr(element, "tag"): @@ -173,13 +169,10 @@ def serializeElement(element): serializeElement(element) - if finalText is not None: - rv.append("%s\"" % (' ' * 2, finalText)) - return "".join(rv) -class TreeBuilder(_base.TreeBuilder): +class TreeBuilder(base.TreeBuilder): documentClass = Document doctypeClass = DocumentType elementClass = None @@ -189,13 +182,15 @@ class TreeBuilder(_base.TreeBuilder): def __init__(self, namespaceHTMLElements, fullTree=False): builder = etree_builders.getETreeModule(etree, fullTree=fullTree) - infosetFilter = self.infosetFilter = ihatexml.InfosetFilter() + infosetFilter = self.infosetFilter = _ihatexml.InfosetFilter(preventDoubleDashComments=True) self.namespaceHTMLElements = namespaceHTMLElements class Attributes(dict): - def __init__(self, element, value={}): + def __init__(self, element, value=None): + if value is None: + value = {} self._element = element - dict.__init__(self, value) + dict.__init__(self, value) # pylint:disable=non-parent-init-called for key, value in self.items(): if isinstance(key, tuple): name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1])) @@ -257,12 +252,12 @@ def _getData(self): data = property(_getData, _setData) self.elementClass = Element - self.commentClass = builder.Comment + self.commentClass = Comment # self.fragmentClass = builder.DocumentFragment - _base.TreeBuilder.__init__(self, namespaceHTMLElements) + base.TreeBuilder.__init__(self, namespaceHTMLElements) def reset(self): - _base.TreeBuilder.reset(self) + base.TreeBuilder.reset(self) self.insertComment = self.insertCommentInitial self.initial_comments = [] self.doctype = None @@ -303,19 +298,21 @@ def insertDoctype(self, token): self.doctype = doctype def insertCommentInitial(self, data, parent=None): + assert parent is None or parent is self.document + assert self.document._elementTree is None self.initial_comments.append(data) def insertCommentMain(self, data, parent=None): if (parent == self.document and self.document._elementTree.getroot()[-1].tag == comment_type): - warnings.warn("lxml cannot represent adjacent comments beyond the root elements", DataLossWarning) + warnings.warn("lxml cannot represent adjacent comments beyond the root elements", DataLossWarning) super(TreeBuilder, self).insertComment(data, parent) def insertRoot(self, token): """Create the document root""" # Because of the way libxml2 works, it doesn't seem to be possible to # alter information like the doctype after the tree has been parsed. - # Therefore we need to use the built-in parser to create our iniial + # Therefore we need to use the built-in parser to create our initial # tree, after which we can add elements like normal docStr = "" if self.doctype: @@ -344,7 +341,8 @@ def insertRoot(self, token): # Append the initial comments: for comment_token in self.initial_comments: - root.addprevious(etree.Comment(comment_token["data"])) + comment = self.commentClass(comment_token["data"]) + root.addprevious(comment._element) # Create the root document and add the ElementTree to it self.document = self.documentClass() diff --git a/pip/_vendor/html5lib/treewalkers/__init__.py b/pip/_vendor/html5lib/treewalkers/__init__.py --- a/pip/_vendor/html5lib/treewalkers/__init__.py +++ b/pip/_vendor/html5lib/treewalkers/__init__.py @@ -10,13 +10,10 @@ from __future__ import absolute_import, division, unicode_literals -__all__ = ["getTreeWalker", "pprint", "dom", "etree", "genshistream", "lxmletree", - "pulldom"] - -import sys - from .. import constants -from ..utils import default_etree +from .._utils import default_etree + +__all__ = ["getTreeWalker", "pprint", "dom", "etree", "genshi", "etree_lxml"] treeWalkerCache = {} @@ -24,34 +21,33 @@ def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support - treeType - the name of the tree type required (case-insensitive). Supported - values are: + Args: + treeType (str): the name of the tree type required (case-insensitive). + Supported values are: - "dom" - The xml.dom.minidom DOM implementation - "pulldom" - The xml.dom.pulldom event stream - "etree" - A generic walker for tree implementations exposing an - elementtree-like interface (known to work with - ElementTree, cElementTree and lxml.etree). - "lxml" - Optimized walker for lxml.etree - "genshi" - a Genshi stream + - "dom": The xml.dom.minidom DOM implementation + - "etree": A generic walker for tree implementations exposing an + elementtree-like interface (known to work with + ElementTree, cElementTree and lxml.etree). + - "lxml": Optimized walker for lxml.etree + - "genshi": a Genshi stream - implementation - (Currently applies to the "etree" tree type only). A module - implementing the tree type e.g. xml.etree.ElementTree or - cElementTree.""" + Implementation: A module implementing the tree type e.g. + xml.etree.ElementTree or cElementTree (Currently applies to the + "etree" tree type only). + """ treeType = treeType.lower() if treeType not in treeWalkerCache: - if treeType in ("dom", "pulldom"): - name = "%s.%s" % (__name__, treeType) - __import__(name) - mod = sys.modules[name] - treeWalkerCache[treeType] = mod.TreeWalker + if treeType == "dom": + from . import dom + treeWalkerCache[treeType] = dom.TreeWalker elif treeType == "genshi": - from . import genshistream - treeWalkerCache[treeType] = genshistream.TreeWalker + from . import genshi + treeWalkerCache[treeType] = genshi.TreeWalker elif treeType == "lxml": - from . import lxmletree - treeWalkerCache[treeType] = lxmletree.TreeWalker + from . import etree_lxml + treeWalkerCache[treeType] = etree_lxml.TreeWalker elif treeType == "etree": from . import etree if implementation is None: diff --git a/pip/_vendor/html5lib/treewalkers/_base.py b/pip/_vendor/html5lib/treewalkers/base.py similarity index 58% rename from pip/_vendor/html5lib/treewalkers/_base.py rename to pip/_vendor/html5lib/treewalkers/base.py --- a/pip/_vendor/html5lib/treewalkers/_base.py +++ b/pip/_vendor/html5lib/treewalkers/base.py @@ -1,11 +1,11 @@ from __future__ import absolute_import, division, unicode_literals -from pip._vendor.six import text_type, string_types + +from xml.dom import Node +from ..constants import namespaces, voidElements, spaceCharacters __all__ = ["DOCUMENT", "DOCTYPE", "TEXT", "ELEMENT", "COMMENT", "ENTITY", "UNKNOWN", "TreeWalker", "NonRecursiveTreeWalker"] -from xml.dom import Node - DOCUMENT = Node.DOCUMENT_NODE DOCTYPE = Node.DOCUMENT_TYPE_NODE TEXT = Node.TEXT_NODE @@ -14,28 +14,9 @@ ENTITY = Node.ENTITY_NODE UNKNOWN = "<#UNKNOWN#>" -from ..constants import voidElements, spaceCharacters spaceCharacters = "".join(spaceCharacters) -def to_text(s, blank_if_none=True): - """Wrapper around six.text_type to convert None to empty string""" - if s is None: - if blank_if_none: - return "" - else: - return None - elif isinstance(s, text_type): - return s - else: - return text_type(s) - - -def is_text_or_none(string): - """Wrapper around isinstance(string_types) or is None""" - return string is None or isinstance(string, string_types) - - class TreeWalker(object): def __init__(self, tree): self.tree = tree @@ -47,47 +28,25 @@ def error(self, msg): return {"type": "SerializeError", "data": msg} def emptyTag(self, namespace, name, attrs, hasChildren=False): - assert namespace is None or isinstance(namespace, string_types), type(namespace) - assert isinstance(name, string_types), type(name) - 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()) - - yield {"type": "EmptyTag", "name": to_text(name, False), - "namespace": to_text(namespace), + yield {"type": "EmptyTag", "name": name, + "namespace": namespace, "data": attrs} if hasChildren: yield self.error("Void element has children") def startTag(self, namespace, name, attrs): - assert namespace is None or isinstance(namespace, string_types), type(namespace) - assert isinstance(name, string_types), type(name) - 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()) - 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())} + "name": name, + "namespace": namespace, + "data": attrs} def endTag(self, namespace, name): - assert namespace is None or isinstance(namespace, string_types), type(namespace) - assert isinstance(name, string_types), type(namespace) - return {"type": "EndTag", - "name": to_text(name, False), - "namespace": to_text(namespace), - "data": {}} + "name": name, + "namespace": namespace} def text(self, data): - assert isinstance(data, string_types), type(data) - - data = to_text(data) + data = data middle = data.lstrip(spaceCharacters) left = data[:len(data) - len(middle)] if left: @@ -101,25 +60,16 @@ def text(self, data): yield {"type": "SpaceCharacters", "data": right} def comment(self, data): - assert isinstance(data, string_types), type(data) - - return {"type": "Comment", "data": text_type(data)} - - def doctype(self, name, publicId=None, systemId=None, correct=True): - assert is_text_or_none(name), type(name) - assert is_text_or_none(publicId), type(publicId) - assert is_text_or_none(systemId), type(systemId) + return {"type": "Comment", "data": data} + def doctype(self, name, publicId=None, systemId=None): return {"type": "Doctype", - "name": to_text(name), - "publicId": to_text(publicId), - "systemId": to_text(systemId), - "correct": to_text(correct)} + "name": name, + "publicId": publicId, + "systemId": systemId} def entity(self, name): - assert isinstance(name, string_types), type(name) - - return {"type": "Entity", "name": text_type(name)} + return {"type": "Entity", "name": name} def unknown(self, nodeType): return self.error("Unknown node type: " + nodeType) @@ -154,7 +104,7 @@ def __iter__(self): elif type == ELEMENT: namespace, name, attributes, hasChildren = details - if name in voidElements: + if (not namespace or namespace == namespaces["html"]) and name in voidElements: for token in self.emptyTag(namespace, name, attributes, hasChildren): yield token @@ -187,7 +137,7 @@ def __iter__(self): type, details = details[0], details[1:] if type == ELEMENT: namespace, name, attributes, hasChildren = details - if name not in voidElements: + if (namespace and namespace != namespaces["html"]) or name not in voidElements: yield self.endTag(namespace, name) if self.tree is currentNode: currentNode = None diff --git a/pip/_vendor/html5lib/treewalkers/dom.py b/pip/_vendor/html5lib/treewalkers/dom.py --- a/pip/_vendor/html5lib/treewalkers/dom.py +++ b/pip/_vendor/html5lib/treewalkers/dom.py @@ -2,16 +2,16 @@ from xml.dom import Node -from . import _base +from . import base -class TreeWalker(_base.NonRecursiveTreeWalker): +class TreeWalker(base.NonRecursiveTreeWalker): def getNodeDetails(self, node): if node.nodeType == Node.DOCUMENT_TYPE_NODE: - return _base.DOCTYPE, node.name, node.publicId, node.systemId + return base.DOCTYPE, node.name, node.publicId, node.systemId elif node.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): - return _base.TEXT, node.nodeValue + return base.TEXT, node.nodeValue elif node.nodeType == Node.ELEMENT_NODE: attrs = {} @@ -21,17 +21,17 @@ def getNodeDetails(self, node): attrs[(attr.namespaceURI, attr.localName)] = attr.value else: attrs[(None, attr.name)] = attr.value - return (_base.ELEMENT, node.namespaceURI, node.nodeName, + return (base.ELEMENT, node.namespaceURI, node.nodeName, attrs, node.hasChildNodes()) elif node.nodeType == Node.COMMENT_NODE: - return _base.COMMENT, node.nodeValue + return base.COMMENT, node.nodeValue elif node.nodeType in (Node.DOCUMENT_NODE, Node.DOCUMENT_FRAGMENT_NODE): - return (_base.DOCUMENT,) + return (base.DOCUMENT,) else: - return _base.UNKNOWN, node.nodeType + return base.UNKNOWN, node.nodeType def getFirstChild(self, node): return node.firstChild diff --git a/pip/_vendor/html5lib/treewalkers/etree.py b/pip/_vendor/html5lib/treewalkers/etree.py --- a/pip/_vendor/html5lib/treewalkers/etree.py +++ b/pip/_vendor/html5lib/treewalkers/etree.py @@ -10,10 +10,10 @@ import re -from pip._vendor.six import text_type +from pip._vendor. import string_types -from . import _base -from ..utils import moduleFactoryFactory +from . import base +from .._utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") @@ -22,7 +22,7 @@ def getETreeBuilder(ElementTreeImplementation): ElementTree = ElementTreeImplementation ElementTreeCommentType = ElementTree.Comment("asd").tag - class TreeWalker(_base.NonRecursiveTreeWalker): + class TreeWalker(base.NonRecursiveTreeWalker): # pylint:disable=unused-variable """Given the particular ElementTree representation, this implementation, to avoid using recursion, returns "nodes" as tuples with the following content: @@ -38,9 +38,9 @@ class TreeWalker(_base.NonRecursiveTreeWalker): """ def getNodeDetails(self, node): if isinstance(node, tuple): # It might be the root Element - elt, key, parents, flag = node + elt, _, _, flag = node if flag in ("text", "tail"): - return _base.TEXT, getattr(elt, flag) + return base.TEXT, getattr(elt, flag) else: node = elt @@ -48,14 +48,14 @@ def getNodeDetails(self, node): node = node.getroot() if node.tag in ("DOCUMENT_ROOT", "DOCUMENT_FRAGMENT"): - return (_base.DOCUMENT,) + return (base.DOCUMENT,) elif node.tag == "<!DOCTYPE>": - return (_base.DOCTYPE, node.text, + return (base.DOCTYPE, node.text, node.get("publicId"), node.get("systemId")) elif node.tag == ElementTreeCommentType: - return _base.COMMENT, node.text + return base.COMMENT, node.text else: assert isinstance(node.tag, string_types), type(node.tag) @@ -73,7 +73,7 @@ def getNodeDetails(self, node): attrs[(match.group(1), match.group(2))] = value else: attrs[(None, name)] = value - return (_base.ELEMENT, namespace, tag, + return (base.ELEMENT, namespace, tag, attrs, len(node) or node.text) def getFirstChild(self, node): @@ -129,6 +129,7 @@ def getParentNode(self, node): if not parents: return parent else: + assert list(parents[-1]).count(parent) == 1 return parent, list(parents[-1]).index(parent), parents, None return locals() diff --git a/pip/_vendor/html5lib/treewalkers/lxmletree.py b/pip/_vendor/html5lib/treewalkers/etree_lxml.py similarity index 77% rename from pip/_vendor/html5lib/treewalkers/lxmletree.py rename to pip/_vendor/html5lib/treewalkers/etree_lxml.py --- a/pip/_vendor/html5lib/treewalkers/lxmletree.py +++ b/pip/_vendor/html5lib/treewalkers/etree_lxml.py @@ -4,9 +4,9 @@ from lxml import etree from ..treebuilders.etree import tag_regexp -from . import _base +from . import base -from .. import ihatexml +from .. import _ihatexml def ensure_str(s): @@ -15,20 +15,27 @@ def ensure_str(s): elif isinstance(s, text_type): return s else: - return s.decode("utf-8", "strict") + return s.decode("ascii", "strict") class Root(object): def __init__(self, et): self.elementtree = et self.children = [] - if et.docinfo.internalDTD: - self.children.append(Doctype(self, - ensure_str(et.docinfo.root_name), - ensure_str(et.docinfo.public_id), - ensure_str(et.docinfo.system_url))) - root = et.getroot() - node = root + + try: + if et.docinfo.internalDTD: + self.children.append(Doctype(self, + ensure_str(et.docinfo.root_name), + ensure_str(et.docinfo.public_id), + ensure_str(et.docinfo.system_url))) + except AttributeError: + pass + + try: + node = et.getroot() + except AttributeError: + node = et while node.getprevious() is not None: node = node.getprevious() @@ -115,35 +122,38 @@ def __len__(self): return len(self.obj) -class TreeWalker(_base.NonRecursiveTreeWalker): +class TreeWalker(base.NonRecursiveTreeWalker): def __init__(self, tree): - if hasattr(tree, "getroot"): - tree = Root(tree) - elif isinstance(tree, list): + # pylint:disable=redefined-variable-type + if isinstance(tree, list): + self.fragmentChildren = set(tree) tree = FragmentRoot(tree) - _base.NonRecursiveTreeWalker.__init__(self, tree) - self.filter = ihatexml.InfosetFilter() + else: + self.fragmentChildren = set() + tree = Root(tree) + base.NonRecursiveTreeWalker.__init__(self, tree) + self.filter = _ihatexml.InfosetFilter() def getNodeDetails(self, node): if isinstance(node, tuple): # Text node node, key = node assert key in ("text", "tail"), "Text nodes are text or tail, found %s" % key - return _base.TEXT, ensure_str(getattr(node, key)) + return base.TEXT, ensure_str(getattr(node, key)) elif isinstance(node, Root): - return (_base.DOCUMENT,) + return (base.DOCUMENT,) elif isinstance(node, Doctype): - return _base.DOCTYPE, node.name, node.public_id, node.system_id + return base.DOCTYPE, node.name, node.public_id, node.system_id elif isinstance(node, FragmentWrapper) and not hasattr(node, "tag"): - return _base.TEXT, node.obj + return base.TEXT, ensure_str(node.obj) elif node.tag == etree.Comment: - return _base.COMMENT, ensure_str(node.text) + return base.COMMENT, ensure_str(node.text) elif node.tag == etree.Entity: - return _base.ENTITY, ensure_str(node.text)[1:-1] # strip &; + return base.ENTITY, ensure_str(node.text)[1:-1] # strip &; else: # This is assumed to be an ordinary element @@ -162,7 +172,7 @@ def getNodeDetails(self, node): attrs[(match.group(1), match.group(2))] = value else: attrs[(None, name)] = value - return (_base.ELEMENT, namespace, self.filter.fromXmlName(tag), + return (base.ELEMENT, namespace, self.filter.fromXmlName(tag), attrs, len(node) > 0 or node.text) def getFirstChild(self, node): @@ -197,5 +207,7 @@ def getParentNode(self, node): if key == "text": return node # else: fallback to "normal" processing + elif node in self.fragmentChildren: + return None return node.getparent() diff --git a/pip/_vendor/html5lib/treewalkers/genshistream.py b/pip/_vendor/html5lib/treewalkers/genshi.py similarity index 90% rename from pip/_vendor/html5lib/treewalkers/genshistream.py rename to pip/_vendor/html5lib/treewalkers/genshi.py --- a/pip/_vendor/html5lib/treewalkers/genshistream.py +++ b/pip/_vendor/html5lib/treewalkers/genshi.py @@ -4,12 +4,12 @@ from genshi.core import START, END, XML_NAMESPACE, DOCTYPE, TEXT from genshi.core import START_NS, END_NS, START_CDATA, END_CDATA, PI, COMMENT -from . import _base +from . import base from ..constants import voidElements, namespaces -class TreeWalker(_base.TreeWalker): +class TreeWalker(base.TreeWalker): def __iter__(self): # Buffer the events so we can pass in the following one previous = None @@ -25,7 +25,7 @@ def __iter__(self): yield token def tokens(self, event, next): - kind, data, pos = event + kind, data, _ = event if kind == START: tag, attribs = data name = tag.localname @@ -39,8 +39,8 @@ def tokens(self, event, next): if namespace == namespaces["html"] and name in voidElements: for token in self.emptyTag(namespace, name, converted_attribs, - not next or next[0] != END - or next[1] != tag): + not next or next[0] != END or + next[1] != tag): yield token else: yield self.startTag(namespace, name, converted_attribs) @@ -48,7 +48,7 @@ def tokens(self, event, next): elif kind == END: name = data.localname namespace = data.namespace - if name not in voidElements: + if namespace != namespaces["html"] or name not in voidElements: yield self.endTag(namespace, name) elif kind == COMMENT: diff --git a/pip/_vendor/html5lib/treewalkers/pulldom.py b/pip/_vendor/html5lib/treewalkers/pulldom.py deleted file mode 100644 --- a/pip/_vendor/html5lib/treewalkers/pulldom.py +++ /dev/null @@ -1,63 +0,0 @@ -from __future__ import absolute_import, division, unicode_literals - -from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ - COMMENT, IGNORABLE_WHITESPACE, CHARACTERS - -from . import _base - -from ..constants import voidElements - - -class TreeWalker(_base.TreeWalker): - def __iter__(self): - ignore_until = None - previous = None - for event in self.tree: - if previous is not None and \ - (ignore_until is None or previous[1] is ignore_until): - if previous[1] is ignore_until: - ignore_until = None - for token in self.tokens(previous, event): - yield token - if token["type"] == "EmptyTag": - ignore_until = previous[1] - previous = event - if ignore_until is None or previous[1] is ignore_until: - for token in self.tokens(previous, None): - yield token - elif ignore_until is not None: - raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") - - def tokens(self, event, next): - type, node = event - if type == START_ELEMENT: - name = node.nodeName - namespace = node.namespaceURI - attrs = {} - for attr in list(node.attributes.keys()): - attr = node.getAttributeNode(attr) - attrs[(attr.namespaceURI, attr.localName)] = attr.value - if name in voidElements: - for token in self.emptyTag(namespace, - name, - attrs, - not next or next[1] is not node): - yield token - else: - yield self.startTag(namespace, name, attrs) - - elif type == END_ELEMENT: - name = node.nodeName - namespace = node.namespaceURI - if name not in voidElements: - yield self.endTag(namespace, name) - - elif type == COMMENT: - yield self.comment(node.nodeValue) - - elif type in (IGNORABLE_WHITESPACE, CHARACTERS): - for token in self.text(node.nodeValue): - yield token - - else: - yield self.unknown(type) diff --git a/pip/_vendor/ipaddress.py b/pip/_vendor/ipaddress.py --- a/pip/_vendor/ipaddress.py +++ b/pip/_vendor/ipaddress.py @@ -14,7 +14,7 @@ import itertools import struct -__version__ = '1.0.16' +__version__ = '1.0.17' # Compatibility functions _compat_int_types = (int,) @@ -759,12 +759,12 @@ def __getitem__(self, n): broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: - raise IndexError + raise IndexError('address out of range') return self._address_class(network + n) else: n += 1 if broadcast + n < network: - raise IndexError + raise IndexError('address out of range') return self._address_class(broadcast + n) def __lt__(self, other): @@ -866,21 +866,21 @@ def address_exclude(self, other): addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') - addr1.address_exclude(addr2) = + list(addr1.address_exclude(addr2)) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), - IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] + IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') - addr1.address_exclude(addr2) = + list(addr1.address_exclude(addr2)) = [ip_network('2001:db8::1/128'), - ip_network('2001:db8::2/127'), - ip_network('2001:db8::4/126'), - ip_network('2001:db8::8/125'), - ... - ip_network('2001:db8:8000::/33')] + ip_network('2001:db8::2/127'), + ip_network('2001:db8::4/126'), + ip_network('2001:db8::8/125'), + ... + ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. @@ -1039,7 +1039,7 @@ def subnets(self, prefixlen_diff=1, new_prefix=None): new_prefixlen, self)) start = int(self.network_address) - end = int(self.broadcast_address) + end = int(self.broadcast_address) + 1 step = (int(self.hostmask) + 1) >> prefixlen_diff for new_addr in _compat_range(start, end, step): current = self.__class__((new_addr, new_prefixlen)) @@ -1435,6 +1435,12 @@ def is_private(self): """ return any(self in net for net in self._constants._private_networks) + @property + def is_global(self): + return ( + self not in self._constants._public_network and + not self.is_private) + @property def is_multicast(self): """Test if the address is reserved for multicast use. @@ -1682,6 +1688,8 @@ class _IPv4Constants(object): _multicast_network = IPv4Network('224.0.0.0/4') + _public_network = IPv4Network('100.64.0.0/10') + _private_networks = [ IPv4Network('0.0.0.0/8'), IPv4Network('10.0.0.0/8'), diff --git a/pip/_vendor/ordereddict.py b/pip/_vendor/ordereddict.py new file mode 100644 --- /dev/null +++ b/pip/_vendor/ordereddict.py @@ -0,0 +1,127 @@ +# Copyright (c) 2009 Raymond Hettinger +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation files +# (the "Software"), to deal in the Software without restriction, +# including without limitation the rights to use, copy, modify, merge, +# publish, distribute, sublicense, and/or sell copies of the Software, +# and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# OTHER DEALINGS IN THE SOFTWARE. + +from UserDict import DictMixin + +class OrderedDict(dict, DictMixin): + + def __init__(self, *args, **kwds): + if len(args) > 1: + raise TypeError('expected at most 1 arguments, got %d' % len(args)) + try: + self.__end + except AttributeError: + self.clear() + self.update(*args, **kwds) + + def clear(self): + self.__end = end = [] + end += [None, end, end] # sentinel node for doubly linked list + self.__map = {} # key --> [key, prev, next] + dict.clear(self) + + def __setitem__(self, key, value): + if key not in self: + end = self.__end + curr = end[1] + curr[2] = end[1] = self.__map[key] = [key, curr, end] + dict.__setitem__(self, key, value) + + def __delitem__(self, key): + dict.__delitem__(self, key) + key, prev, next = self.__map.pop(key) + prev[2] = next + next[1] = prev + + def __iter__(self): + end = self.__end + curr = end[2] + while curr is not end: + yield curr[0] + curr = curr[2] + + def __reversed__(self): + end = self.__end + curr = end[1] + while curr is not end: + yield curr[0] + curr = curr[1] + + def popitem(self, last=True): + if not self: + raise KeyError('dictionary is empty') + if last: + key = reversed(self).next() + else: + key = iter(self).next() + value = self.pop(key) + return key, value + + def __reduce__(self): + items = [[k, self[k]] for k in self] + tmp = self.__map, self.__end + del self.__map, self.__end + inst_dict = vars(self).copy() + self.__map, self.__end = tmp + if inst_dict: + return (self.__class__, (items,), inst_dict) + return self.__class__, (items,) + + def keys(self): + return list(self) + + setdefault = DictMixin.setdefault + update = DictMixin.update + pop = DictMixin.pop + values = DictMixin.values + items = DictMixin.items + iterkeys = DictMixin.iterkeys + itervalues = DictMixin.itervalues + iteritems = DictMixin.iteritems + + def __repr__(self): + if not self: + return '%s()' % (self.__class__.__name__,) + return '%s(%r)' % (self.__class__.__name__, self.items()) + + def copy(self): + return self.__class__(self) + + @classmethod + def fromkeys(cls, iterable, value=None): + d = cls() + for key in iterable: + d[key] = value + return d + + def __eq__(self, other): + if isinstance(other, OrderedDict): + if len(self) != len(other): + return False + for p, q in zip(self.items(), other.items()): + if p != q: + return False + return True + return dict.__eq__(self, other) + + def __ne__(self, other): + return not self == other diff --git a/pip/_vendor/packaging/__about__.py b/pip/_vendor/packaging/__about__.py --- a/pip/_vendor/packaging/__about__.py +++ b/pip/_vendor/packaging/__about__.py @@ -12,7 +12,7 @@ __summary__ = "Core utilities for Python packages" __uri__ = "https://github.com/pypa/packaging" -__version__ = "16.7" +__version__ = "16.8" __author__ = "Donald Stufft and individual contributors" __email__ = "donald@stufft.io" diff --git a/pip/_vendor/packaging/markers.py b/pip/_vendor/packaging/markers.py --- a/pip/_vendor/packaging/markers.py +++ b/pip/_vendor/packaging/markers.py @@ -54,13 +54,26 @@ def __str__(self): def __repr__(self): return "<{0}({1!r})>".format(self.__class__.__name__, str(self)) + def serialize(self): + raise NotImplementedError + class Variable(Node): - pass + + def serialize(self): + return str(self) class Value(Node): - pass + + def serialize(self): + return '"{0}"'.format(self) + + +class Op(Node): + + def serialize(self): + return str(self) VARIABLE = ( @@ -105,6 +118,7 @@ class Value(Node): ) MARKER_OP = VERSION_CMP | L("not in") | L("in") +MARKER_OP.setParseAction(lambda s, l, t: Op(t[0])) MARKER_VALUE = QuotedString("'") | QuotedString('"') MARKER_VALUE.setParseAction(lambda s, l, t: Value(t[0])) @@ -151,7 +165,7 @@ def _format_marker(marker, first=True): else: return "(" + " ".join(inner) + ")" elif isinstance(marker, tuple): - return '{0} {1} "{2}"'.format(*marker) + return " ".join([m.serialize() for m in marker]) else: return marker @@ -170,13 +184,13 @@ def _format_marker(marker, first=True): def _eval_op(lhs, op, rhs): try: - spec = Specifier("".join([op, rhs])) + spec = Specifier("".join([op.serialize(), rhs])) except InvalidSpecifier: pass else: return spec.contains(lhs) - oper = _operators.get(op) + oper = _operators.get(op.serialize()) if oper is None: raise UndefinedComparison( "Undefined {0!r} on {1!r} and {2!r}.".format(op, lhs, rhs) diff --git a/pip/_vendor/pyparsing.py b/pip/_vendor/pyparsing.py --- a/pip/_vendor/pyparsing.py +++ b/pip/_vendor/pyparsing.py @@ -1,6 +1,6 @@ # module pyparsing.py # -# Copyright (c) 2003-2015 Paul T. McGuire +# Copyright (c) 2003-2016 Paul T. McGuire # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -31,15 +31,18 @@ don't need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python. -Here is a program to parse "Hello, World!" (or any greeting of the form C{"<salutation>, <addressee>!"}):: +Here is a program to parse "Hello, World!" (or any greeting of the form +C{"<salutation>, <addressee>!"}), built up using L{Word}, L{Literal}, and L{And} elements +(L{'+'<ParserElement.__add__>} operator gives L{And} expressions, strings are auto-converted to +L{Literal} expressions):: from pyparsing import Word, alphas # define grammar of a greeting - greet = Word( alphas ) + "," + Word( alphas ) + "!" + greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" - print (hello, "->", greet.parseString( hello )) + print (hello, "->", greet.parseString(hello)) The program outputs the following:: @@ -48,7 +51,7 @@ The Python representation of the grammar is quite readable, owing to the self-explanatory class names, and the use of '+', '|' and '^' operators. -The parsed results returned from C{parseString()} can be accessed as a nested list, a dictionary, or an +The L{ParseResults} object returned from L{ParserElement.parseString<ParserElement.parseString>} can be accessed as a nested list, a dictionary, or an object with named attributes. The pyparsing module handles some of the problems that are typically vexing when writing text parsers: @@ -57,8 +60,8 @@ class names, and the use of '+', '|' and '^' operators. - embedded comments """ -__version__ = "2.1.1" -__versionTime__ = "21 Mar 2016 05:04 UTC" +__version__ = "2.1.10" +__versionTime__ = "07 Oct 2016 01:31 UTC" __author__ = "Paul McGuire <ptmcg@users.sourceforge.net>" import string @@ -70,9 +73,22 @@ class names, and the use of '+', '|' and '^' operators. import sre_constants import collections import pprint -import functools -import itertools import traceback +import types +from datetime import datetime + +try: + from _thread import RLock +except ImportError: + from threading import RLock + +try: + from collections import OrderedDict as _OrderedDict +except ImportError: + try: + from ordereddict import OrderedDict as _OrderedDict + except ImportError: + _OrderedDict = None #~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) ) @@ -94,9 +110,11 @@ class names, and the use of '+', '|' and '^' operators. 'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd', 'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute', 'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation','locatedExpr', 'withClass', +'CloseMatch', 'tokenMap', 'pyparsing_common', ] -PY_3 = sys.version.startswith('3') +system_version = tuple(sys.version_info)[:3] +PY_3 = system_version[0] == 3 if PY_3: _MAX_INT = sys.maxsize basestring = str @@ -174,6 +192,15 @@ def __init__( self, pstr, loc=0, msg=None, elem=None ): self.msg = msg self.pstr = pstr self.parserElement = elem + self.args = (pstr, loc, msg) + + @classmethod + def _from_exception(cls, pe): + """ + internal factory method to simplify creating one type of ParseException + from another - avoids having __init__ signature conflicts among subclasses + """ + return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) def __getattr__( self, aname ): """supported attributes by name are: @@ -209,11 +236,23 @@ def __dir__(self): return "lineno col line".split() + dir(type(self)) class ParseException(ParseBaseException): - """exception thrown when parse expressions don't match class; - supported attributes by name are: - - lineno - returns the line number of the exception text - - col - returns the column number of the exception text - - line - returns the line containing the exception text + """ + Exception thrown when parse expressions don't match class; + supported attributes by name are: + - lineno - returns the line number of the exception text + - col - returns the column number of the exception text + - line - returns the line containing the exception text + + Example:: + try: + Word(nums).setName("integer").parseString("ABC") + except ParseException as pe: + print(pe) + print("column: {}".format(pe.col)) + + prints:: + Expected integer (at char 0), (line:1, col:1) + column: 1 """ pass @@ -223,12 +262,10 @@ class ParseFatalException(ParseBaseException): pass class ParseSyntaxException(ParseFatalException): - """just like C{L{ParseFatalException}}, but thrown internally when an - C{L{ErrorStop<And._ErrorStop>}} ('-' operator) indicates that parsing is to stop immediately because - an unbacktrackable syntax error has been found""" - def __init__(self, pe): - super(ParseSyntaxException, self).__init__( - pe.pstr, pe.loc, pe.msg, pe.parserElement) + """just like L{ParseFatalException}, but thrown internally when an + L{ErrorStop<And._ErrorStop>} ('-' operator) indicates that parsing is to stop + immediately because an unbacktrackable syntax error has been found""" + pass #~ class ReparseException(ParseBaseException): #~ """Experimental class - parse actions can raise this exception to cause @@ -244,7 +281,7 @@ def __init__(self, pe): #~ self.reparseLoc = restartLoc class RecursiveGrammarException(Exception): - """exception thrown by C{validate()} if the grammar could be improperly recursive""" + """exception thrown by L{ParserElement.validate} if the grammar could be improperly recursive""" def __init__( self, parseElementList ): self.parseElementTrace = parseElementList @@ -257,16 +294,49 @@ def __init__(self,p1,p2): def __getitem__(self,i): return self.tup[i] def __repr__(self): - return repr(self.tup) + return repr(self.tup[0]) def setOffset(self,i): self.tup = (self.tup[0],i) class ParseResults(object): - """Structured parse results, to provide multiple means of access to the parsed data: + """ + Structured parse results, to provide multiple means of access to the parsed data: - as a list (C{len(results)}) - by list index (C{results[0], results[1]}, etc.) - - by attribute (C{results.<resultsName>}) - """ + - by attribute (C{results.<resultsName>} - see L{ParserElement.setResultsName}) + + Example:: + integer = Word(nums) + date_str = (integer.setResultsName("year") + '/' + + integer.setResultsName("month") + '/' + + integer.setResultsName("day")) + # equivalent form: + # date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + # parseString returns a ParseResults object + result = date_str.parseString("1999/12/31") + + def test(s, fn=repr): + print("%s -> %s" % (s, fn(eval(s)))) + test("list(result)") + test("result[0]") + test("result['month']") + test("result.day") + test("'month' in result") + test("'minutes' in result") + test("result.dump()", str) + prints:: + list(result) -> ['1999', '/', '12', '/', '31'] + result[0] -> '1999' + result['month'] -> '12' + result.day -> '31' + 'month' in result -> True + 'minutes' in result -> False + result.dump() -> ['1999', '/', '12', '/', '31'] + - day: 31 + - month: 12 + - year: 1999 + """ def __new__(cls, toklist=None, name=None, asList=True, modal=True ): if isinstance(toklist, cls): return toklist @@ -351,11 +421,6 @@ def __delitem__( self, i ): removed = list(range(*i.indices(mylen))) removed.reverse() # fixup indices in token dictionary - #~ for name in self.__tokdict: - #~ occurrences = self.__tokdict[name] - #~ for j in removed: - #~ for k, (value, position) in enumerate(occurrences): - #~ occurrences[k] = _ParseResultsWithOffset(value, position - (position > j)) for name,occurrences in self.__tokdict.items(): for j in removed: for k, (value, position) in enumerate(occurrences): @@ -371,35 +436,48 @@ def __bool__(self): return ( not not self.__toklist ) __nonzero__ = __bool__ def __iter__( self ): return iter( self.__toklist ) def __reversed__( self ): return iter( self.__toklist[::-1] ) - def iterkeys( self ): - """Returns all named result keys.""" + def _iterkeys( self ): if hasattr(self.__tokdict, "iterkeys"): return self.__tokdict.iterkeys() else: return iter(self.__tokdict) - def itervalues( self ): - """Returns all named result values.""" - return (self[k] for k in self.iterkeys()) + def _itervalues( self ): + return (self[k] for k in self._iterkeys()) - def iteritems( self ): - return ((k, self[k]) for k in self.iterkeys()) + def _iteritems( self ): + return ((k, self[k]) for k in self._iterkeys()) if PY_3: - keys = iterkeys - values = itervalues - items = iteritems + keys = _iterkeys + """Returns an iterator of all named result keys (Python 3.x only).""" + + values = _itervalues + """Returns an iterator of all named result values (Python 3.x only).""" + + items = _iteritems + """Returns an iterator of all named result key-value tuples (Python 3.x only).""" + else: + iterkeys = _iterkeys + """Returns an iterator of all named result keys (Python 2.x only).""" + + itervalues = _itervalues + """Returns an iterator of all named result values (Python 2.x only).""" + + iteritems = _iteritems + """Returns an iterator of all named result key-value tuples (Python 2.x only).""" + def keys( self ): - """Returns all named result keys.""" + """Returns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x).""" return list(self.iterkeys()) def values( self ): - """Returns all named result values.""" + """Returns all named result values (as a list in Python 2.x, as an iterator in Python 3.x).""" return list(self.itervalues()) def items( self ): - """Returns all named result keys and values as a list of tuples.""" + """Returns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x).""" return list(self.iteritems()) def haskeys( self ): @@ -408,14 +486,39 @@ def haskeys( self ): return bool(self.__tokdict) def pop( self, *args, **kwargs): - """Removes and returns item at specified index (default=last). - Supports both list and dict semantics for pop(). If passed no - argument or an integer argument, it will use list semantics - and pop tokens from the list of parsed tokens. If passed a - non-integer argument (most likely a string), it will use dict - semantics and pop the corresponding value from any defined - results names. A second default return value argument is - supported, just as in dict.pop().""" + """ + Removes and returns item at specified index (default=C{last}). + Supports both C{list} and C{dict} semantics for C{pop()}. If passed no + argument or an integer argument, it will use C{list} semantics + and pop tokens from the list of parsed tokens. If passed a + non-integer argument (most likely a string), it will use C{dict} + semantics and pop the corresponding value from any defined + results names. A second default return value argument is + supported, just as in C{dict.pop()}. + + Example:: + def remove_first(tokens): + tokens.pop(0) + print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] + print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321'] + + label = Word(alphas) + patt = label("LABEL") + OneOrMore(Word(nums)) + print(patt.parseString("AAB 123 321").dump()) + + # Use pop() in a parse action to remove named result (note that corresponding value is not + # removed from list form of results) + def remove_LABEL(tokens): + tokens.pop("LABEL") + return tokens + patt.addParseAction(remove_LABEL) + print(patt.parseString("AAB 123 321").dump()) + prints:: + ['AAB', '123', '321'] + - LABEL: AAB + + ['AAB', '123', '321'] + """ if not args: args = [-1] for k,v in kwargs.items(): @@ -435,39 +538,83 @@ def pop( self, *args, **kwargs): return defaultvalue def get(self, key, defaultValue=None): - """Returns named result matching the given key, or if there is no - such name, then returns the given C{defaultValue} or C{None} if no - C{defaultValue} is specified.""" + """ + Returns named result matching the given key, or if there is no + such name, then returns the given C{defaultValue} or C{None} if no + C{defaultValue} is specified. + + Similar to C{dict.get()}. + + Example:: + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parseString("1999/12/31") + print(result.get("year")) # -> '1999' + print(result.get("hour", "not specified")) # -> 'not specified' + print(result.get("hour")) # -> None + """ if key in self: return self[key] else: return defaultValue def insert( self, index, insStr ): - """Inserts new element at location index in the list of parsed tokens.""" + """ + Inserts new element at location index in the list of parsed tokens. + + Similar to C{list.insert()}. + + Example:: + print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] + + # use a parse action to insert the parse location in the front of the parsed results + def insert_locn(locn, tokens): + tokens.insert(0, locn) + print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321'] + """ self.__toklist.insert(index, insStr) # fixup indices in token dictionary - #~ for name in self.__tokdict: - #~ occurrences = self.__tokdict[name] - #~ for k, (value, position) in enumerate(occurrences): - #~ occurrences[k] = _ParseResultsWithOffset(value, position + (position > index)) for name,occurrences in self.__tokdict.items(): for k, (value, position) in enumerate(occurrences): occurrences[k] = _ParseResultsWithOffset(value, position + (position > index)) def append( self, item ): - """Add single element to end of ParseResults list of elements.""" + """ + Add single element to end of ParseResults list of elements. + + Example:: + print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321'] + + # use a parse action to compute the sum of the parsed integers, and add it to the end + def append_sum(tokens): + tokens.append(sum(map(int, tokens))) + print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444] + """ self.__toklist.append(item) def extend( self, itemseq ): - """Add sequence of elements to end of ParseResults list of elements.""" + """ + Add sequence of elements to end of ParseResults list of elements. + + Example:: + patt = OneOrMore(Word(alphas)) + + # use a parse action to append the reverse of the matched strings, to make a palindrome + def make_palindrome(tokens): + tokens.extend(reversed([t[::-1] for t in tokens])) + return ''.join(tokens) + print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' + """ if isinstance(itemseq, ParseResults): self += itemseq else: self.__toklist.extend(itemseq) def clear( self ): - """Clear all elements and results names.""" + """ + Clear all elements and results names. + """ del self.__toklist[:] self.__tokdict.clear() @@ -532,11 +679,40 @@ def _asStringList( self, sep='' ): return out def asList( self ): - """Returns the parse results as a nested list of matching tokens, all converted to strings.""" + """ + Returns the parse results as a nested list of matching tokens, all converted to strings. + + Example:: + patt = OneOrMore(Word(alphas)) + result = patt.parseString("sldkj lsdkj sldkj") + # even though the result prints in string-like form, it is actually a pyparsing ParseResults + print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj'] + + # Use asList() to create an actual list + result_list = result.asList() + print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj'] + """ return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist] def asDict( self ): - """Returns the named parse results as a nested dictionary.""" + """ + Returns the named parse results as a nested dictionary. + + Example:: + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parseString('12/31/1999') + print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) + + result_dict = result.asDict() + print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'} + + # even though a ParseResults supports dict-like access, sometime you just need to have a dict + import json + print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable + print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"} + """ if PY_3: item_fn = self.items else: @@ -554,7 +730,9 @@ def toItem(obj): return dict((k,toItem(v)) for k,v in item_fn()) def copy( self ): - """Returns a new copy of a C{ParseResults} object.""" + """ + Returns a new copy of a C{ParseResults} object. + """ ret = ParseResults( self.__toklist ) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent @@ -563,7 +741,9 @@ def copy( self ): return ret def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ): - """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.""" + """ + (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. + """ nl = "\n" out = [] namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items() @@ -629,7 +809,27 @@ def __lookup(self,sub): return None def getName(self): - """Returns the results name for this token expression.""" + """ + Returns the results name for this token expression. Useful when several + different expressions might match at a particular location. + + Example:: + integer = Word(nums) + ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") + house_number_expr = Suppress('#') + Word(nums, alphanums) + user_data = (Group(house_number_expr)("house_number") + | Group(ssn_expr)("ssn") + | Group(integer)("age")) + user_info = OneOrMore(user_data) + + result = user_info.parseString("22 111-22-3333 #221B") + for item in result: + print(item.getName(), ':', item[0]) + prints:: + age : 22 + ssn : 111-22-3333 + house_number : 221B + """ if self.__name: return self.__name elif self.__parent: @@ -640,45 +840,77 @@ def getName(self): return None elif (len(self) == 1 and len(self.__tokdict) == 1 and - self.__tokdict.values()[0][0][1] in (0,-1)): - return self.__tokdict.keys()[0] + next(iter(self.__tokdict.values()))[0][1] in (0,-1)): + return next(iter(self.__tokdict.keys())) else: return None - def dump(self,indent='',depth=0): - """Diagnostic method for listing out the contents of a C{ParseResults}. - Accepts an optional C{indent} argument so that this string can be embedded - in a nested display of other data.""" + def dump(self, indent='', depth=0, full=True): + """ + Diagnostic method for listing out the contents of a C{ParseResults}. + Accepts an optional C{indent} argument so that this string can be embedded + in a nested display of other data. + + Example:: + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + result = date_str.parseString('12/31/1999') + print(result.dump()) + prints:: + ['12', '/', '31', '/', '1999'] + - day: 1999 + - month: 31 + - year: 12 + """ out = [] NL = '\n' out.append( indent+_ustr(self.asList()) ) - if self.haskeys(): - items = sorted(self.items()) - for k,v in items: - if out: - out.append(NL) - out.append( "%s%s- %s: " % (indent,(' '*depth), k) ) - if isinstance(v,ParseResults): - if v: - out.append( v.dump(indent,depth+1) ) + if full: + if self.haskeys(): + items = sorted((str(k), v) for k,v in self.items()) + for k,v in items: + if out: + out.append(NL) + out.append( "%s%s- %s: " % (indent,(' '*depth), k) ) + if isinstance(v,ParseResults): + if v: + out.append( v.dump(indent,depth+1) ) + else: + out.append(_ustr(v)) else: - out.append(_ustr(v)) - else: - out.append(_ustr(v)) - elif any(isinstance(vv,ParseResults) for vv in self): - v = self - for i,vv in enumerate(v): - if isinstance(vv,ParseResults): - out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),vv.dump(indent,depth+1) )) - else: - out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),_ustr(vv))) + out.append(repr(v)) + elif any(isinstance(vv,ParseResults) for vv in self): + v = self + for i,vv in enumerate(v): + if isinstance(vv,ParseResults): + out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),vv.dump(indent,depth+1) )) + else: + out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),_ustr(vv))) return "".join(out) def pprint(self, *args, **kwargs): - """Pretty-printer for parsed results as a list, using the C{pprint} module. - Accepts additional positional or keyword args as defined for the - C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})""" + """ + Pretty-printer for parsed results as a list, using the C{pprint} module. + Accepts additional positional or keyword args as defined for the + C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint}) + + Example:: + ident = Word(alphas, alphanums) + num = Word(nums) + func = Forward() + term = ident | num | Group('(' + func + ')') + func <<= ident + Group(Optional(delimitedList(term))) + result = func.parseString("fna a,b,(fnb c,d,200),100") + result.pprint(width=40) + prints:: + ['fna', + ['a', + 'b', + ['(', 'fnb', ['c', 'd', '200'], ')'], + '100']] + """ pprint.pprint(self.asList(), *args, **kwargs) # add support for pickle protocol @@ -721,7 +953,7 @@ def col (loc,strg): positions within the parsed string. """ s = strg - return 1 if loc<len(s) and s[loc] == '\n' else loc - s.rfind("\n", 0, loc) + return 1 if 0<loc<len(s) and s[loc-1] == '\n' else loc - s.rfind("\n", 0, loc) def lineno(loc,strg): """Returns current line number within a string, counting newlines as line separators. @@ -786,10 +1018,35 @@ def _trim_arity(func, maxargs=2): return lambda s,l,t: func(t) limit = [0] foundArity = [False] + + # traceback return data structure changed in Py3.5 - normalize back to plain tuples + if system_version[:2] >= (3,5): + def extract_stack(limit=0): + # special handling for Python 3.5.0 - extra deep call stack by 1 + offset = -3 if system_version == (3,5,0) else -2 + frame_summary = traceback.extract_stack(limit=-offset+limit-1)[offset] + return [(frame_summary.filename, frame_summary.lineno)] + def extract_tb(tb, limit=0): + frames = traceback.extract_tb(tb, limit=limit) + frame_summary = frames[-1] + return [(frame_summary.filename, frame_summary.lineno)] + else: + extract_stack = traceback.extract_stack + extract_tb = traceback.extract_tb + + # synthesize what would be returned by traceback.extract_stack at the call to + # user's parse action 'func', so that we don't incur call penalty at parse time + + LINE_DIFF = 6 + # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND + # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!! + this_line = extract_stack(limit=2)[-1] + pa_call_line_synth = (this_line[0], this_line[1]+LINE_DIFF) + def wrapper(*args): while 1: try: - ret = func(*args[limit[0]:]) #~@$^*)+_(&%#!=-`~;:"[]{} + ret = func(*args[limit[0]:]) foundArity[0] = True return ret except TypeError: @@ -799,8 +1056,7 @@ def wrapper(*args): else: try: tb = sys.exc_info()[-1] - exc_source_line = traceback.extract_tb(tb)[-1][-1] - if not exc_source_line.endswith('#~@$^*)+_(&%#!=-`~;:"[]{}'): + if not extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth: raise finally: del tb @@ -809,6 +1065,16 @@ def wrapper(*args): limit[0] += 1 continue raise + + # copy func name to wrapper for sensible debug output + func_name = "<parse action>" + try: + func_name = getattr(func, '__name__', + getattr(func, '__class__').__name__) + except Exception: + func_name = str(func) + wrapper.__name__ = func_name + return wrapper class ParserElement(object): @@ -818,7 +1084,16 @@ class ParserElement(object): @staticmethod def setDefaultWhitespaceChars( chars ): - """Overrides the default whitespace chars + r""" + Overrides the default whitespace chars + + Example:: + # default whitespace chars are space, <TAB> and newline + OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl'] + + # change to just treat newline as significant + ParserElement.setDefaultWhitespaceChars(" \t") + OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def'] """ ParserElement.DEFAULT_WHITE_CHARS = chars @@ -826,8 +1101,22 @@ def setDefaultWhitespaceChars( chars ): def inlineLiteralsUsing(cls): """ Set class to be used for inclusion of string literals into a parser. + + Example:: + # default literal class used is Literal + integer = Word(nums) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] + + + # change to Suppress + ParserElement.inlineLiteralsUsing(Suppress) + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") + + date_str.parseString("1999/12/31") # -> ['1999', '12', '31'] """ - ParserElement.literalStringClass = cls + ParserElement._literalStringClass = cls def __init__( self, savelist=False ): self.parseAction = list() @@ -853,8 +1142,21 @@ def __init__( self, savelist=False ): self.callDuringTry = False def copy( self ): - """Make a copy of this C{ParserElement}. Useful for defining different parse actions - for the same parsing pattern, using copies of the original parse element.""" + """ + Make a copy of this C{ParserElement}. Useful for defining different parse actions + for the same parsing pattern, using copies of the original parse element. + + Example:: + integer = Word(nums).setParseAction(lambda toks: int(toks[0])) + integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K") + integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") + + print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M")) + prints:: + [5120, 100, 655360, 268435456] + Equivalent form of C{expr.copy()} is just C{expr()}:: + integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M") + """ cpy = copy.copy( self ) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] @@ -863,7 +1165,13 @@ def copy( self ): return cpy def setName( self, name ): - """Define name for this expression, for use in debugging.""" + """ + Define name for this expression, makes debugging and exception messages clearer. + + Example:: + Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) + Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1) + """ self.name = name self.errmsg = "Expected " + self.name if hasattr(self,"exception"): @@ -871,15 +1179,24 @@ def setName( self, name ): return self def setResultsName( self, name, listAllMatches=False ): - """Define name for referencing matching tokens as a nested attribute - of the returned parse results. - NOTE: this returns a *copy* of the original C{ParserElement} object; - this is so that the client can define a basic element, such as an - integer, and reference it in multiple places with different names. - - You can also set results names using the abbreviated syntax, - C{expr("name")} in place of C{expr.setResultsName("name")} - - see L{I{__call__}<__call__>}. + """ + Define name for referencing matching tokens as a nested attribute + of the returned parse results. + NOTE: this returns a *copy* of the original C{ParserElement} object; + this is so that the client can define a basic element, such as an + integer, and reference it in multiple places with different names. + + You can also set results names using the abbreviated syntax, + C{expr("name")} in place of C{expr.setResultsName("name")} - + see L{I{__call__}<__call__>}. + + Example:: + date_str = (integer.setResultsName("year") + '/' + + integer.setResultsName("month") + '/' + + integer.setResultsName("day")) + + # equivalent form: + date_str = integer("year") + '/' + integer("month") + '/' + integer("day") """ newself = self.copy() if name.endswith("*"): @@ -908,42 +1225,76 @@ def breaker(instring, loc, doActions=True, callPreParse=True): return self def setParseAction( self, *fns, **kwargs ): - """Define action to perform when successfully matching parse element definition. - Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, - C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - - s = the original string being parsed (see note below) - - loc = the location of the matching substring - - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object - If the functions in fns modify the tokens, they can return them as the return - value from fn, and the modified list of tokens will replace the original. - Otherwise, fn does not need to return any value. - - Note: the default parsing behavior is to expand tabs in the input string - before starting the parsing process. See L{I{parseString}<parseString>} for more information - on parsing strings containing C{<TAB>}s, and suggested methods to maintain a - consistent view of the parsed string, the parse location, and line and column - positions within the parsed string. - """ + """ + Define action to perform when successfully matching parse element definition. + Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, + C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: + - s = the original string being parsed (see note below) + - loc = the location of the matching substring + - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object + If the functions in fns modify the tokens, they can return them as the return + value from fn, and the modified list of tokens will replace the original. + Otherwise, fn does not need to return any value. + + Optional keyword arguments: + - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing + + Note: the default parsing behavior is to expand tabs in the input string + before starting the parsing process. See L{I{parseString}<parseString>} for more information + on parsing strings containing C{<TAB>}s, and suggested methods to maintain a + consistent view of the parsed string, the parse location, and line and column + positions within the parsed string. + + Example:: + integer = Word(nums) + date_str = integer + '/' + integer + '/' + integer + + date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] + + # use parse action to convert to ints at parse time + integer = Word(nums).setParseAction(lambda toks: int(toks[0])) + date_str = integer + '/' + integer + '/' + integer + + # note that integer fields are now ints, not strings + date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] + """ self.parseAction = list(map(_trim_arity, list(fns))) self.callDuringTry = kwargs.get("callDuringTry", False) return self def addParseAction( self, *fns, **kwargs ): - """Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.""" + """ + Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}. + + See examples in L{I{copy}<copy>}. + """ self.parseAction += list(map(_trim_arity, list(fns))) self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) return self def addCondition(self, *fns, **kwargs): """Add a boolean predicate function to expression's list of parse actions. See - L{I{setParseAction}<setParseAction>}. Optional keyword argument C{message} can - be used to define a custom message to be used in the raised exception.""" - msg = kwargs.get("message") or "failed user-defined condition" + L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction}, + functions passed to C{addCondition} need to return boolean success/fail of the condition. + + Optional keyword arguments: + - message = define a custom message to be used in the raised exception + - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException + + Example:: + integer = Word(nums).setParseAction(lambda toks: int(toks[0])) + year_int = integer.copy() + year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later") + date_str = year_int + '/' + integer + '/' + integer + + result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1) + """ + msg = kwargs.get("message", "failed user-defined condition") + exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException for fn in fns: def pa(s,l,t): if not bool(_trim_arity(fn)(s,l,t)): - raise ParseException(s,l,msg) - return t + raise exc_type(s,l,msg) self.parseAction.append(pa) self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False) return self @@ -1079,42 +1430,123 @@ def canParseNext(self, instring, loc): else: return True + class _UnboundedCache(object): + def __init__(self): + cache = {} + self.not_in_cache = not_in_cache = object() + + def get(self, key): + return cache.get(key, not_in_cache) + + def set(self, key, value): + cache[key] = value + + def clear(self): + cache.clear() + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set, self) + self.clear = types.MethodType(clear, self) + + if _OrderedDict is not None: + class _FifoCache(object): + def __init__(self, size): + self.not_in_cache = not_in_cache = object() + + cache = _OrderedDict() + + def get(self, key): + return cache.get(key, not_in_cache) + + def set(self, key, value): + cache[key] = value + if len(cache) > size: + cache.popitem(False) + + def clear(self): + cache.clear() + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set, self) + self.clear = types.MethodType(clear, self) + + else: + class _FifoCache(object): + def __init__(self, size): + self.not_in_cache = not_in_cache = object() + + cache = {} + key_fifo = collections.deque([], size) + + def get(self, key): + return cache.get(key, not_in_cache) + + def set(self, key, value): + cache[key] = value + if len(cache) > size: + cache.pop(key_fifo.popleft(), None) + key_fifo.append(key) + + def clear(self): + cache.clear() + key_fifo.clear() + + self.get = types.MethodType(get, self) + self.set = types.MethodType(set, self) + self.clear = types.MethodType(clear, self) + + # argument cache for optimizing repeated calls when backtracking through recursive expressions + packrat_cache = {} # this is set later by enabledPackrat(); this is here so that resetCache() doesn't fail + packrat_cache_lock = RLock() + packrat_cache_stats = [0, 0] + # this method gets repeatedly called during backtracking with the same arguments - # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression def _parseCache( self, instring, loc, doActions=True, callPreParse=True ): - lookup = (self,instring,loc,callPreParse,doActions) - if lookup in ParserElement._exprArgCache: - value = ParserElement._exprArgCache[ lookup ] - if isinstance(value, Exception): - raise value - return (value[0],value[1].copy()) - else: - try: - value = self._parseNoCache( instring, loc, doActions, callPreParse ) - ParserElement._exprArgCache[ lookup ] = (value[0],value[1].copy()) - return value - except ParseBaseException as pe: - pe.__traceback__ = None - ParserElement._exprArgCache[ lookup ] = pe - raise + HIT, MISS = 0, 1 + lookup = (self, instring, loc, callPreParse, doActions) + with ParserElement.packrat_cache_lock: + cache = ParserElement.packrat_cache + value = cache.get(lookup) + if value is cache.not_in_cache: + ParserElement.packrat_cache_stats[MISS] += 1 + try: + value = self._parseNoCache(instring, loc, doActions, callPreParse) + except ParseBaseException as pe: + # cache a copy of the exception, without the traceback + cache.set(lookup, pe.__class__(*pe.args)) + raise + else: + cache.set(lookup, (value[0], value[1].copy())) + return value + else: + ParserElement.packrat_cache_stats[HIT] += 1 + if isinstance(value, Exception): + raise value + return (value[0], value[1].copy()) _parse = _parseNoCache - # argument cache for optimizing repeated calls when backtracking through recursive expressions - _exprArgCache = {} @staticmethod def resetCache(): - ParserElement._exprArgCache.clear() + ParserElement.packrat_cache.clear() + ParserElement.packrat_cache_stats[:] = [0] * len(ParserElement.packrat_cache_stats) _packratEnabled = False @staticmethod - def enablePackrat(): + def enablePackrat(cache_size_limit=128): """Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. - + + Parameters: + - cache_size_limit - (default=C{128}) - if an integer value is provided + will limit the size of the packrat cache; if None is passed, then + the cache size will be unbounded; if 0 is passed, the cache will + be effectively disabled. + This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your @@ -1123,32 +1555,45 @@ def enablePackrat(): C{enablePackrat} before calling C{psyco.full()}. If you do not do this, Python will crash. For best results, call C{enablePackrat()} immediately after importing pyparsing. + + Example:: + import pyparsing + pyparsing.ParserElement.enablePackrat() """ if not ParserElement._packratEnabled: ParserElement._packratEnabled = True + if cache_size_limit is None: + ParserElement.packrat_cache = ParserElement._UnboundedCache() + else: + ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit) ParserElement._parse = ParserElement._parseCache def parseString( self, instring, parseAll=False ): - """Execute the parse expression with the given string. - This is the main interface to the client code, once the complete - expression has been built. - - If you want the grammar to require that the entire input string be - successfully parsed, then set C{parseAll} to True (equivalent to ending - the grammar with C{L{StringEnd()}}). - - Note: C{parseString} implicitly calls C{expandtabs()} on the input string, - in order to report proper column numbers in parse actions. - If the input string contains tabs and - the grammar uses parse actions that use the C{loc} argument to index into the - string being parsed, you can ensure you have a consistent view of the input - string by: - - calling C{parseWithTabs} on your grammar before calling C{parseString} - (see L{I{parseWithTabs}<parseWithTabs>}) - - define your parse action using the full C{(s,loc,toks)} signature, and - reference the input string using the parse action's C{s} argument - - explictly expand the tabs in your input string before calling - C{parseString} + """ + Execute the parse expression with the given string. + This is the main interface to the client code, once the complete + expression has been built. + + If you want the grammar to require that the entire input string be + successfully parsed, then set C{parseAll} to True (equivalent to ending + the grammar with C{L{StringEnd()}}). + + Note: C{parseString} implicitly calls C{expandtabs()} on the input string, + in order to report proper column numbers in parse actions. + If the input string contains tabs and + the grammar uses parse actions that use the C{loc} argument to index into the + string being parsed, you can ensure you have a consistent view of the input + string by: + - calling C{parseWithTabs} on your grammar before calling C{parseString} + (see L{I{parseWithTabs}<parseWithTabs>}) + - define your parse action using the full C{(s,loc,toks)} signature, and + reference the input string using the parse action's C{s} argument + - explictly expand the tabs in your input string before calling + C{parseString} + + Example:: + Word('a').parseString('aaaaabaaa') # -> ['aaaaa'] + Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text """ ParserElement.resetCache() if not self.streamlined: @@ -1174,14 +1619,35 @@ def parseString( self, instring, parseAll=False ): return tokens def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ): - """Scan the input string for expression matches. Each match will return the - matching tokens, start location, and end location. May be called with optional - C{maxMatches} argument, to clip scanning after 'n' matches are found. If - C{overlap} is specified, then overlapping matches will be reported. - - Note that the start and end locations are reported relative to the string - being parsed. See L{I{parseString}<parseString>} for more information on parsing - strings with embedded tabs.""" + """ + Scan the input string for expression matches. Each match will return the + matching tokens, start location, and end location. May be called with optional + C{maxMatches} argument, to clip scanning after 'n' matches are found. If + C{overlap} is specified, then overlapping matches will be reported. + + Note that the start and end locations are reported relative to the string + being parsed. See L{I{parseString}<parseString>} for more information on parsing + strings with embedded tabs. + + Example:: + source = "sldjf123lsdjjkf345sldkjf879lkjsfd987" + print(source) + for tokens,start,end in Word(alphas).scanString(source): + print(' '*start + '^'*(end-start)) + print(' '*start + tokens[0]) + + prints:: + + sldjf123lsdjjkf345sldkjf879lkjsfd987 + ^^^^^ + sldjf + ^^^^^^^ + lsdjjkf + ^^^^^^ + sldkjf + ^^^^^^ + lkjsfd + """ if not self.streamlined: self.streamline() for e in self.ignoreExprs: @@ -1224,12 +1690,22 @@ def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ): raise exc def transformString( self, instring ): - """Extension to C{L{scanString}}, to modify matching text with modified tokens that may - be returned from a parse action. To use C{transformString}, define a grammar and - attach a parse action to it that modifies the returned token list. - Invoking C{transformString()} on a target string will then scan for matches, - and replace the matched text patterns according to the logic in the parse - action. C{transformString()} returns the resulting transformed string.""" + """ + Extension to C{L{scanString}}, to modify matching text with modified tokens that may + be returned from a parse action. To use C{transformString}, define a grammar and + attach a parse action to it that modifies the returned token list. + Invoking C{transformString()} on a target string will then scan for matches, + and replace the matched text patterns according to the logic in the parse + action. C{transformString()} returns the resulting transformed string. + + Example:: + wd = Word(alphas) + wd.setParseAction(lambda toks: toks[0].title()) + + print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york.")) + Prints:: + Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York. + """ out = [] lastE = 0 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to @@ -1257,9 +1733,18 @@ def transformString( self, instring ): raise exc def searchString( self, instring, maxMatches=_MAX_INT ): - """Another extension to C{L{scanString}}, simplifying the access to the tokens found - to match the given parse expression. May be called with optional - C{maxMatches} argument, to clip searching after 'n' matches are found. + """ + Another extension to C{L{scanString}}, simplifying the access to the tokens found + to match the given parse expression. May be called with optional + C{maxMatches} argument, to clip searching after 'n' matches are found. + + Example:: + # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters + cap_word = Word(alphas.upper(), alphas.lower()) + + print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity")) + prints:: + ['More', 'Iron', 'Lead', 'Gold', 'I'] """ try: return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ]) @@ -1270,10 +1755,42 @@ def searchString( self, instring, maxMatches=_MAX_INT ): # catch and re-raise exception from here, clears out pyparsing internal stack trace raise exc + def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): + """ + Generator method to split a string using the given expression as a separator. + May be called with optional C{maxsplit} argument, to limit the number of splits; + and the optional C{includeSeparators} argument (default=C{False}), if the separating + matching text should be included in the split results. + + Example:: + punc = oneOf(list(".,;:/-!?")) + print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) + prints:: + ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] + """ + splits = 0 + last = 0 + for t,s,e in self.scanString(instring, maxMatches=maxsplit): + yield instring[last:s] + if includeSeparators: + yield t[0] + last = e + yield instring[last:] + def __add__(self, other ): - """Implementation of + operator - returns C{L{And}}""" + """ + Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement + converts them to L{Literal}s by default. + + Example:: + greet = Word(alphas) + "," + Word(alphas) + "!" + hello = "Hello, World!" + print (hello, "->", greet.parseString(hello)) + Prints:: + Hello, World! -> ['Hello', ',', 'World', '!'] + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1281,9 +1798,11 @@ def __add__(self, other ): return And( [ self, other ] ) def __radd__(self, other ): - """Implementation of + operator when left operand is not a C{L{ParserElement}}""" + """ + Implementation of + operator when left operand is not a C{L{ParserElement}} + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1291,9 +1810,11 @@ def __radd__(self, other ): return other + self def __sub__(self, other): - """Implementation of - operator, returns C{L{And}} with error stop""" + """ + Implementation of - operator, returns C{L{And}} with error stop + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1301,9 +1822,11 @@ def __sub__(self, other): return And( [ self, And._ErrorStop(), other ] ) def __rsub__(self, other ): - """Implementation of - operator when left operand is not a C{L{ParserElement}}""" + """ + Implementation of - operator when left operand is not a C{L{ParserElement}} + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1311,24 +1834,24 @@ def __rsub__(self, other ): return other - self def __mul__(self,other): - """Implementation of * operator, allows use of C{expr * 3} in place of - C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer - tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples - may also include C{None} as in: - - C{expr*(n,None)} or C{expr*(n,)} is equivalent + """ + Implementation of * operator, allows use of C{expr * 3} in place of + C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer + tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples + may also include C{None} as in: + - C{expr*(n,None)} or C{expr*(n,)} is equivalent to C{expr*n + L{ZeroOrMore}(expr)} (read as "at least n instances of C{expr}") - - C{expr*(None,n)} is equivalent to C{expr*(0,n)} + - C{expr*(None,n)} is equivalent to C{expr*(0,n)} (read as "0 to n instances of C{expr}") - - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)} - - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} - - Note that C{expr*(None,n)} does not raise an exception if - more than n exprs exist in the input stream; that is, - C{expr*(None,n)} does not enforce a maximum number of expr - occurrences. If this behavior is desired, then write - C{expr*(None,n) + ~expr} - + - C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)} + - C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)} + + Note that C{expr*(None,n)} does not raise an exception if + more than n exprs exist in the input stream; that is, + C{expr*(None,n)} does not enforce a maximum number of expr + occurrences. If this behavior is desired, then write + C{expr*(None,n) + ~expr} """ if isinstance(other,int): minElements, optElements = other,0 @@ -1382,9 +1905,11 @@ def __rmul__(self, other): return self.__mul__(other) def __or__(self, other ): - """Implementation of | operator - returns C{L{MatchFirst}}""" + """ + Implementation of | operator - returns C{L{MatchFirst}} + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1392,9 +1917,11 @@ def __or__(self, other ): return MatchFirst( [ self, other ] ) def __ror__(self, other ): - """Implementation of | operator when left operand is not a C{L{ParserElement}}""" + """ + Implementation of | operator when left operand is not a C{L{ParserElement}} + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1402,9 +1929,11 @@ def __ror__(self, other ): return other | self def __xor__(self, other ): - """Implementation of ^ operator - returns C{L{Or}}""" + """ + Implementation of ^ operator - returns C{L{Or}} + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1412,9 +1941,11 @@ def __xor__(self, other ): return Or( [ self, other ] ) def __rxor__(self, other ): - """Implementation of ^ operator when left operand is not a C{L{ParserElement}}""" + """ + Implementation of ^ operator when left operand is not a C{L{ParserElement}} + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1422,9 +1953,11 @@ def __rxor__(self, other ): return other ^ self def __and__(self, other ): - """Implementation of & operator - returns C{L{Each}}""" + """ + Implementation of & operator - returns C{L{Each}} + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1432,9 +1965,11 @@ def __and__(self, other ): return Each( [ self, other ] ) def __rand__(self, other ): - """Implementation of & operator when left operand is not a C{L{ParserElement}}""" + """ + Implementation of & operator when left operand is not a C{L{ParserElement}} + """ if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) @@ -1442,41 +1977,49 @@ def __rand__(self, other ): return other & self def __invert__( self ): - """Implementation of ~ operator - returns C{L{NotAny}}""" + """ + Implementation of ~ operator - returns C{L{NotAny}} + """ return NotAny( self ) def __call__(self, name=None): - """Shortcut for C{L{setResultsName}}, with C{listAllMatches=default}:: - userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") - could be written as:: - userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") - - If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be - passed as C{True}. + """ + Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}. + + If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be + passed as C{True}. - If C{name} is omitted, same as calling C{L{copy}}. - """ + If C{name} is omitted, same as calling C{L{copy}}. + + Example:: + # these are equivalent + userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") + userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") + """ if name is not None: return self.setResultsName(name) else: return self.copy() def suppress( self ): - """Suppresses the output of this C{ParserElement}; useful to keep punctuation from - cluttering up returned output. + """ + Suppresses the output of this C{ParserElement}; useful to keep punctuation from + cluttering up returned output. """ return Suppress( self ) def leaveWhitespace( self ): - """Disables the skipping of whitespace before matching the characters in the - C{ParserElement}'s defined pattern. This is normally only used internally by - the pyparsing module, but may be needed in some whitespace-sensitive grammars. + """ + Disables the skipping of whitespace before matching the characters in the + C{ParserElement}'s defined pattern. This is normally only used internally by + the pyparsing module, but may be needed in some whitespace-sensitive grammars. """ self.skipWhitespace = False return self def setWhitespaceChars( self, chars ): - """Overrides the default whitespace chars + """ + Overrides the default whitespace chars """ self.skipWhitespace = True self.whiteChars = chars @@ -1484,16 +2027,26 @@ def setWhitespaceChars( self, chars ): return self def parseWithTabs( self ): - """Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string. - Must be called before C{parseString} when the input grammar contains elements that - match C{<TAB>} characters.""" + """ + Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string. + Must be called before C{parseString} when the input grammar contains elements that + match C{<TAB>} characters. + """ self.keepTabs = True return self def ignore( self, other ): - """Define expression to be ignored (e.g., comments) while doing pattern - matching; may be called repeatedly, to define multiple comment or other - ignorable patterns. + """ + Define expression to be ignored (e.g., comments) while doing pattern + matching; may be called repeatedly, to define multiple comment or other + ignorable patterns. + + Example:: + patt = OneOrMore(Word(alphas)) + patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'] + + patt.ignore(cStyleComment) + patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd'] """ if isinstance(other, basestring): other = Suppress(other) @@ -1506,7 +2059,9 @@ def ignore( self, other ): return self def setDebugActions( self, startAction, successAction, exceptionAction ): - """Enable display of debugging messages while doing pattern matching.""" + """ + Enable display of debugging messages while doing pattern matching. + """ self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) @@ -1514,8 +2069,40 @@ def setDebugActions( self, startAction, successAction, exceptionAction ): return self def setDebug( self, flag=True ): - """Enable display of debugging messages while doing pattern matching. - Set C{flag} to True to enable, False to disable.""" + """ + Enable display of debugging messages while doing pattern matching. + Set C{flag} to True to enable, False to disable. + + Example:: + wd = Word(alphas).setName("alphaword") + integer = Word(nums).setName("numword") + term = wd | integer + + # turn on debugging for wd + wd.setDebug() + + OneOrMore(term).parseString("abc 123 xyz 890") + + prints:: + Match alphaword at loc 0(1,1) + Matched alphaword -> ['abc'] + Match alphaword at loc 3(1,4) + Exception raised:Expected alphaword (at char 4), (line:1, col:5) + Match alphaword at loc 7(1,8) + Matched alphaword -> ['xyz'] + Match alphaword at loc 11(1,12) + Exception raised:Expected alphaword (at char 12), (line:1, col:13) + Match alphaword at loc 15(1,16) + Exception raised:Expected alphaword (at char 15), (line:1, col:16) + + The output shown is that produced by the default debug actions - custom debug actions can be + specified using L{setDebugActions}. Prior to attempting + to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"} + is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"} + message is shown. Also note the use of L{setName} to assign a human-readable name to the expression, + which makes debugging and exception messages easier to understand - for instance, the default + name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}. + """ if flag: self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction ) else: @@ -1537,20 +2124,22 @@ def checkRecursion( self, parseElementList ): pass def validate( self, validateTrace=[] ): - """Check defined expressions for valid structure, check for infinite recursive definitions.""" + """ + Check defined expressions for valid structure, check for infinite recursive definitions. + """ self.checkRecursion( [] ) def parseFile( self, file_or_filename, parseAll=False ): - """Execute the parse expression on the given file or filename. - If a filename is specified (instead of a file object), - the entire file is opened, read, and closed before parsing. + """ + Execute the parse expression on the given file or filename. + If a filename is specified (instead of a file object), + the entire file is opened, read, and closed before parsing. """ try: file_contents = file_or_filename.read() except AttributeError: - f = open(file_or_filename, "r") - file_contents = f.read() - f.close() + with open(file_or_filename, "r") as f: + file_contents = f.read() try: return self.parseString(file_contents, parseAll) except ParseBaseException as exc: @@ -1564,11 +2153,7 @@ def __eq__(self,other): if isinstance(other, ParserElement): return self is other or vars(self) == vars(other) elif isinstance(other, basestring): - try: - self.parseString(_ustr(other), parseAll=True) - return True - except ParseBaseException: - return False + return self.matches(other) else: return super(ParserElement,self)==other @@ -1584,40 +2169,169 @@ def __req__(self,other): def __rne__(self,other): return not (self == other) - def runTests(self, tests, parseAll=False): - """Execute the parse expression on a series of test strings, showing each - test, the parsed results or where the parse failed. Quick and easy way to - run a parse expression against a list of sample strings. + def matches(self, testString, parseAll=True): + """ + Method for quick testing of a parser against a test string. Good for simple + inline microtests of sub expressions while building up larger parser. - Parameters: - - tests - a list of separate test strings, or a multiline string of test strings - - parseAll - (default=False) - flag to pass to C{L{parseString}} when running tests + Parameters: + - testString - to test against this expression for a match + - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests + + Example:: + expr = Word(nums) + assert expr.matches("100") + """ + try: + self.parseString(_ustr(testString), parseAll=parseAll) + return True + except ParseBaseException: + return False + + def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False): + """ + Execute the parse expression on a series of test strings, showing each + test, the parsed results or where the parse failed. Quick and easy way to + run a parse expression against a list of sample strings. + + Parameters: + - tests - a list of separate test strings, or a multiline string of test strings + - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests + - comment - (default=C{'#'}) - expression for indicating embedded comments in the test + string; pass None to disable comment filtering + - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; + if False, only dump nested list + - printResults - (default=C{True}) prints test output to stdout + - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing + + Returns: a (success, results) tuple, where success indicates that all tests succeeded + (or failed if C{failureTests} is True), and the results contain a list of lines of each + test's output + + Example:: + number_expr = pyparsing_common.number.copy() + + result = number_expr.runTests(''' + # unsigned integer + 100 + # negative integer + -100 + # float with scientific notation + 6.02e23 + # integer with scientific notation + 1e-12 + ''') + print("Success" if result[0] else "Failed!") + + result = number_expr.runTests(''' + # stray character + 100Z + # missing leading digit before '.' + -.100 + # too many '.' + 3.14.159 + ''', failureTests=True) + print("Success" if result[0] else "Failed!") + prints:: + # unsigned integer + 100 + [100] + + # negative integer + -100 + [-100] + + # float with scientific notation + 6.02e23 + [6.02e+23] + + # integer with scientific notation + 1e-12 + [1e-12] + + Success + + # stray character + 100Z + ^ + FAIL: Expected end of text (at char 3), (line:1, col:4) + + # missing leading digit before '.' + -.100 + ^ + FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) + + # too many '.' + 3.14.159 + ^ + FAIL: Expected end of text (at char 4), (line:1, col:5) + + Success + + Each test string must be on a single line. If you want to test a string that spans multiple + lines, create a test like this:: + + expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") + + (Note that this is a raw string literal, you must include the leading 'r'.) """ if isinstance(tests, basestring): - tests = map(str.strip, tests.splitlines()) + tests = list(map(str.strip, tests.rstrip().splitlines())) + if isinstance(comment, basestring): + comment = Literal(comment) + allResults = [] + comments = [] + success = True for t in tests: - out = [t] + if comment is not None and comment.matches(t, False) or comments and not t: + comments.append(t) + continue + if not t: + continue + out = ['\n'.join(comments), t] + comments = [] try: - out.append(self.parseString(t, parseAll=parseAll).dump()) - except ParseException as pe: + t = t.replace(r'\n','\n') + result = self.parseString(t, parseAll=parseAll) + out.append(result.dump(full=fullDump)) + success = success and not failureTests + except ParseBaseException as pe: + fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else "" if '\n' in t: out.append(line(pe.loc, t)) - out.append(' '*(col(pe.loc,t)-1) + '^') + out.append(' '*(col(pe.loc,t)-1) + '^' + fatal) else: - out.append(' '*pe.loc + '^') - out.append(str(pe)) - out.append('') - print('\n'.join(out)) + out.append(' '*pe.loc + '^' + fatal) + out.append("FAIL: " + str(pe)) + success = success and failureTests + result = pe + except Exception as exc: + out.append("FAIL-EXCEPTION: " + str(exc)) + success = success and failureTests + result = exc + + if printResults: + if fullDump: + out.append('') + print('\n'.join(out)) + + allResults.append((t, result)) + + return success, allResults class Token(ParserElement): - """Abstract C{ParserElement} subclass, for defining atomic matching patterns.""" + """ + Abstract C{ParserElement} subclass, for defining atomic matching patterns. + """ def __init__( self ): super(Token,self).__init__( savelist=False ) class Empty(Token): - """An empty token, will always match.""" + """ + An empty token, will always match. + """ def __init__( self ): super(Empty,self).__init__() self.name = "Empty" @@ -1626,7 +2340,9 @@ def __init__( self ): class NoMatch(Token): - """A token that will never match.""" + """ + A token that will never match. + """ def __init__( self ): super(NoMatch,self).__init__() self.name = "NoMatch" @@ -1639,7 +2355,19 @@ def parseImpl( self, instring, loc, doActions=True ): class Literal(Token): - """Token to exactly match a specified string.""" + """ + Token to exactly match a specified string. + + Example:: + Literal('blah').parseString('blah') # -> ['blah'] + Literal('blah').parseString('blahfooblah') # -> ['blah'] + Literal('blah').parseString('bla') # -> Exception: Expected "blah" + + For case-insensitive matching, use L{CaselessLiteral}. + + For keyword matching (force word break before and after the matched string), + use L{Keyword} or L{CaselessKeyword}. + """ def __init__( self, matchString ): super(Literal,self).__init__() self.match = matchString @@ -1665,22 +2393,31 @@ def parseImpl( self, instring, loc, doActions=True ): return loc+self.matchLen, self.match raise ParseException(instring, loc, self.errmsg, self) _L = Literal -ParserElement.literalStringClass = Literal +ParserElement._literalStringClass = Literal class Keyword(Token): - """Token to exactly match a specified string as a keyword, that is, it must be - immediately followed by a non-keyword character. Compare with C{L{Literal}}:: - Literal("if") will match the leading C{'if'} in C{'ifAndOnlyIf'}. - Keyword("if") will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'} - Accepts two optional constructor arguments in addition to the keyword string: - C{identChars} is a string of characters that would be valid identifier characters, - defaulting to all alphanumerics + "_" and "$"; C{caseless} allows case-insensitive - matching, default is C{False}. + """ + Token to exactly match a specified string as a keyword, that is, it must be + immediately followed by a non-keyword character. Compare with C{L{Literal}}: + - C{Literal("if")} will match the leading C{'if'} in C{'ifAndOnlyIf'}. + - C{Keyword("if")} will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'} + Accepts two optional constructor arguments in addition to the keyword string: + - C{identChars} is a string of characters that would be valid identifier characters, + defaulting to all alphanumerics + "_" and "$" + - C{caseless} allows case-insensitive matching, default is C{False}. + + Example:: + Keyword("start").parseString("start") # -> ['start'] + Keyword("start").parseString("starting") # -> Exception + + For case-insensitive matching, use L{CaselessKeyword}. """ DEFAULT_KEYWORD_CHARS = alphanums+"_$" - def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ): + def __init__( self, matchString, identChars=None, caseless=False ): super(Keyword,self).__init__() + if identChars is None: + identChars = Keyword.DEFAULT_KEYWORD_CHARS self.match = matchString self.matchLen = len(matchString) try: @@ -1724,9 +2461,15 @@ def setDefaultKeywordChars( chars ): Keyword.DEFAULT_KEYWORD_CHARS = chars class CaselessLiteral(Literal): - """Token to match a specified string, ignoring case of letters. - Note: the matched results will always be in the case of the given - match string, NOT the case of the input text. + """ + Token to match a specified string, ignoring case of letters. + Note: the matched results will always be in the case of the given + match string, NOT the case of the input text. + + Example:: + OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD'] + + (Contrast with example for L{CaselessKeyword}.) """ def __init__( self, matchString ): super(CaselessLiteral,self).__init__( matchString.upper() ) @@ -1741,7 +2484,15 @@ def parseImpl( self, instring, loc, doActions=True ): raise ParseException(instring, loc, self.errmsg, self) class CaselessKeyword(Keyword): - def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ): + """ + Caseless version of L{Keyword}. + + Example:: + OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD'] + + (Contrast with example for L{CaselessLiteral}.) + """ + def __init__( self, matchString, identChars=None ): super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True ) def parseImpl( self, instring, loc, doActions=True ): @@ -1750,17 +2501,113 @@ def parseImpl( self, instring, loc, doActions=True ): return loc+self.matchLen, self.match raise ParseException(instring, loc, self.errmsg, self) +class CloseMatch(Token): + """ + A variation on L{Literal} which matches "close" matches, that is, + strings with at most 'n' mismatching characters. C{CloseMatch} takes parameters: + - C{match_string} - string to be matched + - C{maxMismatches} - (C{default=1}) maximum number of mismatches allowed to count as a match + + The results from a successful parse will contain the matched text from the input string and the following named results: + - C{mismatches} - a list of the positions within the match_string where mismatches were found + - C{original} - the original match_string used to compare against the input string + + If C{mismatches} is an empty list, then the match was an exact match. + + Example:: + patt = CloseMatch("ATCATCGAATGGA") + patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']}) + patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1) + + # exact match + patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']}) + + # close match allowing up to 2 mismatches + patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2) + patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']}) + """ + def __init__(self, match_string, maxMismatches=1): + super(CloseMatch,self).__init__() + self.name = match_string + self.match_string = match_string + self.maxMismatches = maxMismatches + self.errmsg = "Expected %r (with up to %d mismatches)" % (self.match_string, self.maxMismatches) + self.mayIndexError = False + self.mayReturnEmpty = False + + def parseImpl( self, instring, loc, doActions=True ): + start = loc + instrlen = len(instring) + maxloc = start + len(self.match_string) + + if maxloc <= instrlen: + match_string = self.match_string + match_stringloc = 0 + mismatches = [] + maxMismatches = self.maxMismatches + + for match_stringloc,s_m in enumerate(zip(instring[loc:maxloc], self.match_string)): + src,mat = s_m + if src != mat: + mismatches.append(match_stringloc) + if len(mismatches) > maxMismatches: + break + else: + loc = match_stringloc + 1 + results = ParseResults([instring[start:loc]]) + results['original'] = self.match_string + results['mismatches'] = mismatches + return loc, results + + raise ParseException(instring, loc, self.errmsg, self) + + class Word(Token): - """Token for matching words composed of allowed character sets. - Defined with string containing all allowed initial characters, - an optional string containing allowed body characters (if omitted, - defaults to the initial character set), and an optional minimum, - maximum, and/or exact length. The default value for C{min} is 1 (a - minimum value < 1 is not valid); the default values for C{max} and C{exact} - are 0, meaning no maximum or exact length restriction. An optional - C{excludeChars} parameter can list characters that might be found in - the input C{bodyChars} string; useful to define a word of all printables - except for one or two characters, for instance. + """ + Token for matching words composed of allowed character sets. + Defined with string containing all allowed initial characters, + an optional string containing allowed body characters (if omitted, + defaults to the initial character set), and an optional minimum, + maximum, and/or exact length. The default value for C{min} is 1 (a + minimum value < 1 is not valid); the default values for C{max} and C{exact} + are 0, meaning no maximum or exact length restriction. An optional + C{excludeChars} parameter can list characters that might be found in + the input C{bodyChars} string; useful to define a word of all printables + except for one or two characters, for instance. + + L{srange} is useful for defining custom character set strings for defining + C{Word} expressions, using range notation from regular expression character sets. + + A common mistake is to use C{Word} to match a specific literal string, as in + C{Word("Address")}. Remember that C{Word} uses the string argument to define + I{sets} of matchable characters. This expression would match "Add", "AAA", + "dAred", or any other word made up of the characters 'A', 'd', 'r', 'e', and 's'. + To match an exact literal string, use L{Literal} or L{Keyword}. + + pyparsing includes helper strings for building Words: + - L{alphas} + - L{nums} + - L{alphanums} + - L{hexnums} + - L{alphas8bit} (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.) + - L{punc8bit} (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.) + - L{printables} (any non-whitespace character) + + Example:: + # a word composed of digits + integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9")) + + # a word with a leading capital, and zero or more lowercase + capital_word = Word(alphas.upper(), alphas.lower()) + + # hostnames are alphanumeric, with leading alpha, and '-' + hostname = Word(alphas, alphanums+'-') + + # roman numeral (not a strict parser, accepts invalid mix of characters) + roman = Word("IVXLCDM") + + # any string of non-whitespace characters, except for ',' + csv_value = Word(printables, excludeChars=",") """ def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None ): super(Word,self).__init__() @@ -1813,7 +2660,7 @@ def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword= self.reString = r"\b"+self.reString+r"\b" try: self.re = re.compile( self.reString ) - except: + except Exception: self.re = None def parseImpl( self, instring, loc, doActions=True ): @@ -1854,7 +2701,7 @@ def parseImpl( self, instring, loc, doActions=True ): def __str__( self ): try: return super(Word,self).__str__() - except: + except Exception: pass @@ -1875,8 +2722,17 @@ def charsAsStr(s): class Regex(Token): - """Token for matching strings that match a given regular expression. - Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module. + """ + Token for matching strings that match a given regular expression. + Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module. + If the given regex contains named groups (defined using C{(?P<name>...)}), these will be preserved as + named parse results. + + Example:: + realnum = Regex(r"[+-]?\d+\.\d*") + date = Regex(r'(?P<year>\d{4})-(?P<month>\d\d?)-(?P<day>\d\d?)') + # ref: http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression + roman = Regex(r"M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})") """ compiledREtype = type(re.compile("[A-Z]")) def __init__( self, pattern, flags=0): @@ -1929,7 +2785,7 @@ def parseImpl( self, instring, loc, doActions=True ): def __str__( self ): try: return super(Regex,self).__str__() - except: + except Exception: pass if self.strRepr is None: @@ -1939,18 +2795,31 @@ def __str__( self ): class QuotedString(Token): - """Token for matching strings that are delimited by quoting characters. + r""" + Token for matching strings that are delimited by quoting characters. + + Defined with the following parameters: + - quoteChar - string of one or more characters defining the quote delimiting string + - escChar - character to escape quotes, typically backslash (default=C{None}) + - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=C{None}) + - multiline - boolean indicating whether quotes can span multiple lines (default=C{False}) + - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True}) + - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar) + - convertWhitespaceEscapes - convert escaped whitespace (C{'\t'}, C{'\n'}, etc.) to actual whitespace (default=C{True}) + + Example:: + qs = QuotedString('"') + print(qs.searchString('lsjdf "This is the quote" sldjf')) + complex_qs = QuotedString('{{', endQuoteChar='}}') + print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf')) + sql_qs = QuotedString('"', escQuote='""') + print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf')) + prints:: + [['This is the quote']] + [['This is the "quote"']] + [['This is the quote with "embedded" quotes']] """ def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True): - r"""Defined with the following parameters: - - quoteChar - string of one or more characters defining the quote delimiting string - - escChar - character to escape quotes, typically backslash (default=None) - - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None) - - multiline - boolean indicating whether quotes can span multiple lines (default=C{False}) - - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True}) - - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar) - - convertWhitespaceEscapes - convert escaped whitespace (C{'\t'}, C{'\n'}, etc.) to actual whitespace (default=C{True}) - """ super(QuotedString,self).__init__() # remove white space from quote chars - wont work anyway @@ -2053,7 +2922,7 @@ def parseImpl( self, instring, loc, doActions=True ): def __str__( self ): try: return super(QuotedString,self).__str__() - except: + except Exception: pass if self.strRepr is None: @@ -2063,11 +2932,20 @@ def __str__( self ): class CharsNotIn(Token): - """Token for matching words composed of characters *not* in a given set. - Defined with string containing all disallowed characters, and an optional - minimum, maximum, and/or exact length. The default value for C{min} is 1 (a - minimum value < 1 is not valid); the default values for C{max} and C{exact} - are 0, meaning no maximum or exact length restriction. + """ + Token for matching words composed of characters I{not} in a given set (will + include whitespace in matched characters if not listed in the provided exclusion set - see example). + Defined with string containing all disallowed characters, and an optional + minimum, maximum, and/or exact length. The default value for C{min} is 1 (a + minimum value < 1 is not valid); the default values for C{max} and C{exact} + are 0, meaning no maximum or exact length restriction. + + Example:: + # define a comma-separated-value as anything that is not a ',' + csv_value = CharsNotIn(',') + print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213")) + prints:: + ['dkls', 'lsdkjf', 's12 34', '@!#', '213'] """ def __init__( self, notChars, min=1, max=0, exact=0 ): super(CharsNotIn,self).__init__() @@ -2113,7 +2991,7 @@ def parseImpl( self, instring, loc, doActions=True ): def __str__( self ): try: return super(CharsNotIn, self).__str__() - except: + except Exception: pass if self.strRepr is None: @@ -2125,11 +3003,13 @@ def __str__( self ): return self.strRepr class White(Token): - """Special matching class for matching whitespace. Normally, whitespace is ignored - by pyparsing grammars. This class is included when some whitespace structures - are significant. Define with a string containing the whitespace characters to be - matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments, - as defined for the C{L{Word}} class.""" + """ + Special matching class for matching whitespace. Normally, whitespace is ignored + by pyparsing grammars. This class is included when some whitespace structures + are significant. Define with a string containing the whitespace characters to be + matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments, + as defined for the C{L{Word}} class. + """ whiteStrs = { " " : "<SPC>", "\t": "<TAB>", @@ -2181,7 +3061,9 @@ def __init__( self ): self.mayIndexError = False class GoToColumn(_PositionToken): - """Token to advance to a specific column of input text; useful for tabular report scraping.""" + """ + Token to advance to a specific column of input text; useful for tabular report scraping. + """ def __init__( self, colno ): super(GoToColumn,self).__init__() self.col = colno @@ -2203,28 +3085,41 @@ def parseImpl( self, instring, loc, doActions=True ): ret = instring[ loc: newloc ] return newloc, ret + class LineStart(_PositionToken): - """Matches if current position is at the beginning of a line within the parse string""" + """ + Matches if current position is at the beginning of a line within the parse string + + Example:: + + test = '''\ + AAA this line + AAA and this line + AAA but not this one + B AAA and definitely not this one + ''' + + for t in (LineStart() + 'AAA' + restOfLine).searchString(test): + print(t) + + Prints:: + ['AAA', ' this line'] + ['AAA', ' and this line'] + + """ def __init__( self ): super(LineStart,self).__init__() - self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") ) self.errmsg = "Expected start of line" - def preParse( self, instring, loc ): - preloc = super(LineStart,self).preParse(instring,loc) - if instring[preloc] == "\n": - loc += 1 - return loc - def parseImpl( self, instring, loc, doActions=True ): - if not( loc==0 or - (loc == self.preParse( instring, 0 )) or - (instring[loc-1] == "\n") ): #col(loc, instring) != 1: - raise ParseException(instring, loc, self.errmsg, self) - return loc, [] + if col(loc, instring) == 1: + return loc, [] + raise ParseException(instring, loc, self.errmsg, self) class LineEnd(_PositionToken): - """Matches if current position is at the end of a line within the parse string""" + """ + Matches if current position is at the end of a line within the parse string + """ def __init__( self ): super(LineEnd,self).__init__() self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") ) @@ -2242,7 +3137,9 @@ def parseImpl( self, instring, loc, doActions=True ): raise ParseException(instring, loc, self.errmsg, self) class StringStart(_PositionToken): - """Matches if current position is at the beginning of the parse string""" + """ + Matches if current position is at the beginning of the parse string + """ def __init__( self ): super(StringStart,self).__init__() self.errmsg = "Expected start of text" @@ -2255,7 +3152,9 @@ def parseImpl( self, instring, loc, doActions=True ): return loc, [] class StringEnd(_PositionToken): - """Matches if current position is at the end of the parse string""" + """ + Matches if current position is at the end of the parse string + """ def __init__( self ): super(StringEnd,self).__init__() self.errmsg = "Expected end of text" @@ -2271,11 +3170,12 @@ def parseImpl( self, instring, loc, doActions=True ): raise ParseException(instring, loc, self.errmsg, self) class WordStart(_PositionToken): - """Matches if the current position is at the beginning of a Word, and - is not preceded by any character in a given set of C{wordChars} - (default=C{printables}). To emulate the C{\b} behavior of regular expressions, - use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of - the string being parsed, or at the beginning of a line. + """ + Matches if the current position is at the beginning of a Word, and + is not preceded by any character in a given set of C{wordChars} + (default=C{printables}). To emulate the C{\b} behavior of regular expressions, + use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of + the string being parsed, or at the beginning of a line. """ def __init__(self, wordChars = printables): super(WordStart,self).__init__() @@ -2290,11 +3190,12 @@ def parseImpl(self, instring, loc, doActions=True ): return loc, [] class WordEnd(_PositionToken): - """Matches if the current position is at the end of a Word, and - is not followed by any character in a given set of C{wordChars} - (default=C{printables}). To emulate the C{\b} behavior of regular expressions, - use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of - the string being parsed, or at the end of a line. + """ + Matches if the current position is at the end of a Word, and + is not followed by any character in a given set of C{wordChars} + (default=C{printables}). To emulate the C{\b} behavior of regular expressions, + use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of + the string being parsed, or at the end of a line. """ def __init__(self, wordChars = printables): super(WordEnd,self).__init__() @@ -2312,18 +3213,21 @@ def parseImpl(self, instring, loc, doActions=True ): class ParseExpression(ParserElement): - """Abstract subclass of ParserElement, for combining and post-processing parsed tokens.""" + """ + Abstract subclass of ParserElement, for combining and post-processing parsed tokens. + """ def __init__( self, exprs, savelist = False ): super(ParseExpression,self).__init__(savelist) if isinstance( exprs, _generatorType ): exprs = list(exprs) if isinstance( exprs, basestring ): - self.exprs = [ Literal( exprs ) ] - elif isinstance( exprs, collections.Sequence ): + self.exprs = [ ParserElement._literalStringClass( exprs ) ] + elif isinstance( exprs, collections.Iterable ): + exprs = list(exprs) # if sequence of strings provided, wrap with Literal if all(isinstance(expr, basestring) for expr in exprs): - exprs = map(Literal, exprs) + exprs = map(ParserElement._literalStringClass, exprs) self.exprs = list(exprs) else: try: @@ -2364,7 +3268,7 @@ def ignore( self, other ): def __str__( self ): try: return super(ParseExpression,self).__str__() - except: + except Exception: pass if self.strRepr is None: @@ -2421,9 +3325,19 @@ def copy(self): return ret class And(ParseExpression): - """Requires all given C{ParseExpression}s to be found in the given order. - Expressions may be separated by whitespace. - May be constructed using the C{'+'} operator. + """ + Requires all given C{ParseExpression}s to be found in the given order. + Expressions may be separated by whitespace. + May be constructed using the C{'+'} operator. + May also be constructed using the C{'-'} operator, which will suppress backtracking. + + Example:: + integer = Word(nums) + name_expr = OneOrMore(Word(alphas)) + + expr = And([integer("id"),name_expr("name"),integer("age")]) + # more easily written as: + expr = integer("id") + name_expr("name") + integer("age") """ class _ErrorStop(Empty): @@ -2455,9 +3369,9 @@ def parseImpl( self, instring, loc, doActions=True ): raise except ParseBaseException as pe: pe.__traceback__ = None - raise ParseSyntaxException(pe) + raise ParseSyntaxException._from_exception(pe) except IndexError: - raise ParseSyntaxException( ParseException(instring, len(instring), self.errmsg, self) ) + raise ParseSyntaxException(instring, len(instring), self.errmsg, self) else: loc, exprtokens = e._parse( instring, loc, doActions ) if exprtokens or exprtokens.haskeys(): @@ -2466,7 +3380,7 @@ def parseImpl( self, instring, loc, doActions=True ): def __iadd__(self, other ): if isinstance( other, basestring ): - other = Literal( other ) + other = ParserElement._literalStringClass( other ) return self.append( other ) #And( [ self, other ] ) def checkRecursion( self, parseElementList ): @@ -2487,9 +3401,18 @@ def __str__( self ): class Or(ParseExpression): - """Requires that at least one C{ParseExpression} is found. - If two expressions match, the expression that matches the longest string will be used. - May be constructed using the C{'^'} operator. + """ + Requires that at least one C{ParseExpression} is found. + If two expressions match, the expression that matches the longest string will be used. + May be constructed using the C{'^'} operator. + + Example:: + # construct Or using '^' operator + + number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums)) + print(number.searchString("123 3.1416 789")) + prints:: + [['123'], ['3.1416'], ['789']] """ def __init__( self, exprs, savelist = False ): super(Or,self).__init__(exprs, savelist) @@ -2538,7 +3461,7 @@ def parseImpl( self, instring, loc, doActions=True ): def __ixor__(self, other ): if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) return self.append( other ) #Or( [ self, other ] ) def __str__( self ): @@ -2557,9 +3480,21 @@ def checkRecursion( self, parseElementList ): class MatchFirst(ParseExpression): - """Requires that at least one C{ParseExpression} is found. - If two expressions match, the first one listed is the one that will match. - May be constructed using the C{'|'} operator. + """ + Requires that at least one C{ParseExpression} is found. + If two expressions match, the first one listed is the one that will match. + May be constructed using the C{'|'} operator. + + Example:: + # construct MatchFirst using '|' operator + + # watch the order of expressions to match + number = Word(nums) | Combine(Word(nums) + '.' + Word(nums)) + print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']] + + # put more selective expression first + number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums) + print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']] """ def __init__( self, exprs, savelist = False ): super(MatchFirst,self).__init__(exprs, savelist) @@ -2594,7 +3529,7 @@ def parseImpl( self, instring, loc, doActions=True ): def __ior__(self, other ): if isinstance( other, basestring ): - other = ParserElement.literalStringClass( other ) + other = ParserElement._literalStringClass( other ) return self.append( other ) #MatchFirst( [ self, other ] ) def __str__( self ): @@ -2613,9 +3548,58 @@ def checkRecursion( self, parseElementList ): class Each(ParseExpression): - """Requires all given C{ParseExpression}s to be found, but in any order. - Expressions may be separated by whitespace. - May be constructed using the C{'&'} operator. + """ + Requires all given C{ParseExpression}s to be found, but in any order. + Expressions may be separated by whitespace. + May be constructed using the C{'&'} operator. + + Example:: + color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN") + shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON") + integer = Word(nums) + shape_attr = "shape:" + shape_type("shape") + posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn") + color_attr = "color:" + color("color") + size_attr = "size:" + integer("size") + + # use Each (using operator '&') to accept attributes in any order + # (shape and posn are required, color and size are optional) + shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr) + + shape_spec.runTests(''' + shape: SQUARE color: BLACK posn: 100, 120 + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + color:GREEN size:20 shape:TRIANGLE posn:20,40 + ''' + ) + prints:: + shape: SQUARE color: BLACK posn: 100, 120 + ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']] + - color: BLACK + - posn: ['100', ',', '120'] + - x: 100 + - y: 120 + - shape: SQUARE + + + shape: CIRCLE size: 50 color: BLUE posn: 50,80 + ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']] + - color: BLUE + - posn: ['50', ',', '80'] + - x: 50 + - y: 80 + - shape: CIRCLE + - size: 50 + + + color: GREEN size: 20 shape: TRIANGLE posn: 20,40 + ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']] + - color: GREEN + - posn: ['20', ',', '40'] + - x: 20 + - y: 40 + - shape: TRIANGLE + - size: 20 """ def __init__( self, exprs, savelist = True ): super(Each,self).__init__(exprs, savelist) @@ -2669,17 +3653,7 @@ def parseImpl( self, instring, loc, doActions=True ): loc,results = e._parse(instring,loc,doActions) resultlist.append(results) - finalResults = ParseResults() - for r in resultlist: - dups = {} - for k in r.keys(): - if k in finalResults: - tmp = ParseResults(finalResults[k]) - tmp += ParseResults(r[k]) - dups[k] = tmp - finalResults += ParseResults(r) - for k,v in dups.items(): - finalResults[k] = v + finalResults = sum(resultlist, ParseResults([])) return loc, finalResults def __str__( self ): @@ -2698,11 +3672,16 @@ def checkRecursion( self, parseElementList ): class ParseElementEnhance(ParserElement): - """Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens.""" + """ + Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens. + """ def __init__( self, expr, savelist=False ): super(ParseElementEnhance,self).__init__(savelist) if isinstance( expr, basestring ): - expr = Literal(expr) + if issubclass(ParserElement._literalStringClass, Token): + expr = ParserElement._literalStringClass(expr) + else: + expr = ParserElement._literalStringClass(Literal(expr)) self.expr = expr self.strRepr = None if expr is not None: @@ -2761,7 +3740,7 @@ def validate( self, validateTrace=[] ): def __str__( self ): try: return super(ParseElementEnhance,self).__str__() - except: + except Exception: pass if self.strRepr is None and self.expr is not None: @@ -2770,10 +3749,22 @@ def __str__( self ): class FollowedBy(ParseElementEnhance): - """Lookahead matching of the given parse expression. C{FollowedBy} - does *not* advance the parsing position within the input string, it only + """ + Lookahead matching of the given parse expression. C{FollowedBy} + does I{not} advance the parsing position within the input string, it only verifies that the specified parse expression matches at the current - position. C{FollowedBy} always returns a null token list.""" + position. C{FollowedBy} always returns a null token list. + + Example:: + # use FollowedBy to match a label only if it is followed by a ':' + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) + + OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint() + prints:: + [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']] + """ def __init__( self, expr ): super(FollowedBy,self).__init__(expr) self.mayReturnEmpty = True @@ -2784,11 +3775,16 @@ def parseImpl( self, instring, loc, doActions=True ): class NotAny(ParseElementEnhance): - """Lookahead to disallow matching with the given parse expression. C{NotAny} - does *not* advance the parsing position within the input string, it only - verifies that the specified parse expression does *not* match at the current - position. Also, C{NotAny} does *not* skip over leading whitespace. C{NotAny} - always returns a null token list. May be constructed using the '~' operator.""" + """ + Lookahead to disallow matching with the given parse expression. C{NotAny} + does I{not} advance the parsing position within the input string, it only + verifies that the specified parse expression does I{not} match at the current + position. Also, C{NotAny} does I{not} skip over leading whitespace. C{NotAny} + always returns a null token list. May be constructed using the '~' operator. + + Example:: + + """ def __init__( self, expr ): super(NotAny,self).__init__(expr) #~ self.leaveWhitespace() @@ -2810,21 +3806,13 @@ def __str__( self ): return self.strRepr - -class OneOrMore(ParseElementEnhance): - """Repetition of one or more of the given expression. - - Parameters: - - expr - expression that must match one or more times - - stopOn - (default=None) - expression for a terminating sentinel - (only required if the sentinel would ordinarily match the repetition - expression) - """ +class _MultipleMatch(ParseElementEnhance): def __init__( self, expr, stopOn=None): - super(OneOrMore, self).__init__(expr) + super(_MultipleMatch, self).__init__(expr) + self.saveAsList = True ender = stopOn if isinstance(ender, basestring): - ender = Literal(ender) + ender = ParserElement._literalStringClass(ender) self.not_ender = ~ender if ender is not None else None def parseImpl( self, instring, loc, doActions=True ): @@ -2855,6 +3843,32 @@ def parseImpl( self, instring, loc, doActions=True ): pass return loc, tokens + +class OneOrMore(_MultipleMatch): + """ + Repetition of one or more of the given expression. + + Parameters: + - expr - expression that must match one or more times + - stopOn - (default=C{None}) - expression for a terminating sentinel + (only required if the sentinel would ordinarily match the repetition + expression) + + Example:: + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) + + text = "shape: SQUARE posn: upper left color: BLACK" + OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']] + + # use stopOn attribute for OneOrMore to avoid reading label string as part of the data + attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) + OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']] + + # could also be written as + (attr_expr * (1,)).parseString(text).pprint() + """ def __str__( self ): if hasattr(self,"name"): @@ -2865,19 +3879,17 @@ def __str__( self ): return self.strRepr - def setResultsName( self, name, listAllMatches=False ): - ret = super(OneOrMore,self).setResultsName(name,listAllMatches) - ret.saveAsList = True - return ret - -class ZeroOrMore(OneOrMore): - """Optional repetition of zero or more of the given expression. +class ZeroOrMore(_MultipleMatch): + """ + Optional repetition of zero or more of the given expression. - Parameters: - - expr - expression that must match zero or more times - - stopOn - (default=None) - expression for a terminating sentinel + Parameters: + - expr - expression that must match zero or more times + - stopOn - (default=C{None}) - expression for a terminating sentinel (only required if the sentinel would ordinarily match the repetition expression) + + Example: similar to L{OneOrMore} """ def __init__( self, expr, stopOn=None): super(ZeroOrMore,self).__init__(expr, stopOn=stopOn) @@ -2907,15 +3919,43 @@ def __str__(self): _optionalNotMatched = _NullToken() class Optional(ParseElementEnhance): - """Optional matching of the given expression. - - Parameters: - - expr - expression that must match zero or more times - - default (optional) - value to be returned if the optional expression - is not found. + """ + Optional matching of the given expression. + + Parameters: + - expr - expression that must match zero or more times + - default (optional) - value to be returned if the optional expression is not found. + + Example:: + # US postal code can be a 5-digit zip, plus optional 4-digit qualifier + zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4))) + zip.runTests(''' + # traditional ZIP code + 12345 + + # ZIP+4 form + 12101-0001 + + # invalid ZIP + 98765- + ''') + prints:: + # traditional ZIP code + 12345 + ['12345'] + + # ZIP+4 form + 12101-0001 + ['12101-0001'] + + # invalid ZIP + 98765- + ^ + FAIL: Expected end of text (at char 5), (line:1, col:6) """ def __init__( self, expr, default=_optionalNotMatched ): super(Optional,self).__init__( expr, savelist=False ) + self.saveAsList = self.expr.saveAsList self.defaultValue = default self.mayReturnEmpty = True @@ -2943,17 +3983,59 @@ def __str__( self ): return self.strRepr class SkipTo(ParseElementEnhance): - """Token for skipping over all undefined text until the matched expression is found. + """ + Token for skipping over all undefined text until the matched expression is found. - Parameters: - - expr - target expression marking the end of the data to be skipped - - include - (default=False) if True, the target expression is also parsed + Parameters: + - expr - target expression marking the end of the data to be skipped + - include - (default=C{False}) if True, the target expression is also parsed (the skipped text and target expression are returned as a 2-element list). - - ignore - (default=None) used to define grammars (typically quoted strings and + - ignore - (default=C{None}) used to define grammars (typically quoted strings and comments) that might contain false matches to the target expression - - failOn - (default=None) define expressions that are not allowed to be + - failOn - (default=C{None}) define expressions that are not allowed to be included in the skipped test; if found before the target expression is found, the SkipTo is not a match + + Example:: + report = ''' + Outstanding Issues Report - 1 Jan 2000 + + # | Severity | Description | Days Open + -----+----------+-------------------------------------------+----------- + 101 | Critical | Intermittent system crash | 6 + 94 | Cosmetic | Spelling error on Login ('log|n') | 14 + 79 | Minor | System slow when running too many reports | 47 + ''' + integer = Word(nums) + SEP = Suppress('|') + # use SkipTo to simply match everything up until the next SEP + # - ignore quoted strings, so that a '|' character inside a quoted string does not match + # - parse action will call token.strip() for each matched token, i.e., the description body + string_data = SkipTo(SEP, ignore=quotedString) + string_data.setParseAction(tokenMap(str.strip)) + ticket_expr = (integer("issue_num") + SEP + + string_data("sev") + SEP + + string_data("desc") + SEP + + integer("days_open")) + + for tkt in ticket_expr.searchString(report): + print tkt.dump() + prints:: + ['101', 'Critical', 'Intermittent system crash', '6'] + - days_open: 6 + - desc: Intermittent system crash + - issue_num: 101 + - sev: Critical + ['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14'] + - days_open: 14 + - desc: Spelling error on Login ('log|n') + - issue_num: 94 + - sev: Cosmetic + ['79', 'Minor', 'System slow when running too many reports', '47'] + - days_open: 47 + - desc: System slow when running too many reports + - issue_num: 79 + - sev: Minor """ def __init__( self, other, include=False, ignore=None, failOn=None ): super( SkipTo, self ).__init__( other ) @@ -2963,7 +4045,7 @@ def __init__( self, other, include=False, ignore=None, failOn=None ): self.includeMatch = include self.asList = False if isinstance(failOn, basestring): - self.failOn = Literal(failOn) + self.failOn = ParserElement._literalStringClass(failOn) else: self.failOn = failOn self.errmsg = "No match found for "+_ustr(self.expr) @@ -3016,26 +4098,30 @@ def parseImpl( self, instring, loc, doActions=True ): return loc, skipresult class Forward(ParseElementEnhance): - """Forward declaration of an expression to be defined later - - used for recursive grammars, such as algebraic infix notation. - When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator. - - Note: take care when assigning to C{Forward} not to overlook precedence of operators. - Specifically, '|' has a lower precedence than '<<', so that:: - fwdExpr << a | b | c - will actually be evaluated as:: - (fwdExpr << a) | b | c - thereby leaving b and c out as parseable alternatives. It is recommended that you - explicitly group the values inserted into the C{Forward}:: - fwdExpr << (a | b | c) - Converting to use the '<<=' operator instead will avoid this problem. + """ + Forward declaration of an expression to be defined later - + used for recursive grammars, such as algebraic infix notation. + When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator. + + Note: take care when assigning to C{Forward} not to overlook precedence of operators. + Specifically, '|' has a lower precedence than '<<', so that:: + fwdExpr << a | b | c + will actually be evaluated as:: + (fwdExpr << a) | b | c + thereby leaving b and c out as parseable alternatives. It is recommended that you + explicitly group the values inserted into the C{Forward}:: + fwdExpr << (a | b | c) + Converting to use the '<<=' operator instead will avoid this problem. + + See L{ParseResults.pprint} for an example of a recursive parser created using + C{Forward}. """ def __init__( self, other=None ): super(Forward,self).__init__( other, savelist=False ) def __lshift__( self, other ): if isinstance( other, basestring ): - other = ParserElement.literalStringClass(other) + other = ParserElement._literalStringClass(other) self.expr = other self.strRepr = None self.mayIndexError = self.expr.mayIndexError @@ -3097,15 +4183,29 @@ def __str__( self ): return "..." class TokenConverter(ParseElementEnhance): - """Abstract subclass of C{ParseExpression}, for converting parsed results.""" + """ + Abstract subclass of C{ParseExpression}, for converting parsed results. + """ def __init__( self, expr, savelist=False ): super(TokenConverter,self).__init__( expr )#, savelist ) self.saveAsList = False class Combine(TokenConverter): - """Converter to concatenate all matching tokens to a single string. - By default, the matching patterns must also be contiguous in the input string; - this can be disabled by specifying C{'adjacent=False'} in the constructor. + """ + Converter to concatenate all matching tokens to a single string. + By default, the matching patterns must also be contiguous in the input string; + this can be disabled by specifying C{'adjacent=False'} in the constructor. + + Example:: + real = Word(nums) + '.' + Word(nums) + print(real.parseString('3.1416')) # -> ['3', '.', '1416'] + # will also erroneously match the following + print(real.parseString('3. 1416')) # -> ['3', '.', '1416'] + + real = Combine(Word(nums) + '.' + Word(nums)) + print(real.parseString('3.1416')) # -> ['3.1416'] + # no match when there are internal spaces + print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...) """ def __init__( self, expr, joinString="", adjacent=True ): super(Combine,self).__init__( expr ) @@ -3135,7 +4235,19 @@ def postParse( self, instring, loc, tokenlist ): return retToks class Group(TokenConverter): - """Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions.""" + """ + Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions. + + Example:: + ident = Word(alphas) + num = Word(nums) + term = ident | num + func = ident + Optional(delimitedList(term)) + print(func.parseString("fn a,b,100")) # -> ['fn', 'a', 'b', '100'] + + func = ident + Group(Optional(delimitedList(term))) + print(func.parseString("fn a,b,100")) # -> ['fn', ['a', 'b', '100']] + """ def __init__( self, expr ): super(Group,self).__init__( expr ) self.saveAsList = True @@ -3144,9 +4256,40 @@ def postParse( self, instring, loc, tokenlist ): return [ tokenlist ] class Dict(TokenConverter): - """Converter to return a repetitive expression as a list, but also as a dictionary. - Each element can also be referenced using the first token in the expression as its key. - Useful for tabular report scraping when the first column can be used as a item key. + """ + Converter to return a repetitive expression as a list, but also as a dictionary. + Each element can also be referenced using the first token in the expression as its key. + Useful for tabular report scraping when the first column can be used as a item key. + + Example:: + data_word = Word(alphas) + label = data_word + FollowedBy(':') + attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join)) + + text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) + + # print attributes as plain groups + print(OneOrMore(attr_expr).parseString(text).dump()) + + # instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names + result = Dict(OneOrMore(Group(attr_expr))).parseString(text) + print(result.dump()) + + # access named fields as dict entries, or output as dict + print(result['shape']) + print(result.asDict()) + prints:: + ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap'] + + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: light blue + - posn: upper left + - shape: SQUARE + - texture: burlap + SQUARE + {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'} + See more examples at L{ParseResults} of accessing fields by results name. """ def __init__( self, expr ): super(Dict,self).__init__( expr ) @@ -3178,7 +4321,24 @@ def postParse( self, instring, loc, tokenlist ): class Suppress(TokenConverter): - """Converter for ignoring the results of a parsed expression.""" + """ + Converter for ignoring the results of a parsed expression. + + Example:: + source = "a, b, c,d" + wd = Word(alphas) + wd_list1 = wd + ZeroOrMore(',' + wd) + print(wd_list1.parseString(source)) + + # often, delimiters that are useful during parsing are just in the + # way afterward - use Suppress to keep them out of the parsed output + wd_list2 = wd + ZeroOrMore(Suppress(',') + wd) + print(wd_list2.parseString(source)) + prints:: + ['a', ',', 'b', ',', 'c', ',', 'd'] + ['a', 'b', 'c', 'd'] + (See also L{delimitedList}.) + """ def postParse( self, instring, loc, tokenlist ): return [] @@ -3187,7 +4347,9 @@ def suppress( self ): class OnlyOnce(object): - """Wrapper for parse actions, to ensure they are only called once.""" + """ + Wrapper for parse actions, to ensure they are only called once. + """ def __init__(self, methodCall): self.callable = _trim_arity(methodCall) self.called = False @@ -3201,20 +4363,39 @@ def reset(self): self.called = False def traceParseAction(f): - """Decorator for debugging parse actions.""" + """ + Decorator for debugging parse actions. + + When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".} + When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised. + + Example:: + wd = Word(alphas) + + @traceParseAction + def remove_duplicate_chars(tokens): + return ''.join(sorted(set(''.join(tokens))) + + wds = OneOrMore(wd).setParseAction(remove_duplicate_chars) + print(wds.parseString("slkdjs sld sldd sdlf sdljf")) + prints:: + >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {})) + <<leaving remove_duplicate_chars (ret: 'dfjkls') + ['dfjkls'] + """ f = _trim_arity(f) def z(*paArgs): - thisFunc = f.func_name + thisFunc = f.__name__ s,l,t = paArgs[-3:] if len(paArgs)>3: thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc - sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) ) + sys.stderr.write( ">>entering %s(line: '%s', %d, %r)\n" % (thisFunc,line(l,s),l,t) ) try: ret = f(*paArgs) except Exception as exc: sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) ) raise - sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) ) + sys.stderr.write( "<<leaving %s (ret: %r)\n" % (thisFunc,ret) ) return ret try: z.__name__ = f.__name__ @@ -3226,12 +4407,17 @@ def z(*paArgs): # global helpers # def delimitedList( expr, delim=",", combine=False ): - """Helper to define a delimited list of expressions - the delimiter defaults to ','. - By default, the list elements and delimiters can have intervening whitespace, and - comments, but this can be overridden by passing C{combine=True} in the constructor. - If C{combine} is set to C{True}, the matching tokens are returned as a single token - string, with the delimiters included; otherwise, the matching tokens are returned - as a list of tokens, with the delimiters suppressed. + """ + Helper to define a delimited list of expressions - the delimiter defaults to ','. + By default, the list elements and delimiters can have intervening whitespace, and + comments, but this can be overridden by passing C{combine=True} in the constructor. + If C{combine} is set to C{True}, the matching tokens are returned as a single token + string, with the delimiters included; otherwise, the matching tokens are returned + as a list of tokens, with the delimiters suppressed. + + Example:: + delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc'] + delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE'] """ dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..." if combine: @@ -3240,11 +4426,22 @@ def delimitedList( expr, delim=",", combine=False ): return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName) def countedArray( expr, intExpr=None ): - """Helper to define a counted list of expressions. - This helper defines a pattern of the form:: - integer expr expr expr... - where the leading integer tells how many expr expressions follow. - The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. + """ + Helper to define a counted list of expressions. + This helper defines a pattern of the form:: + integer expr expr expr... + where the leading integer tells how many expr expressions follow. + The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. + + If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value. + + Example:: + countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd'] + + # in this parser, the leading integer value is given in binary, + # '10' indicating that 2 values are in the array + binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2)) + countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd'] """ arrayExpr = Forward() def countFieldParseAction(s,l,t): @@ -3269,16 +4466,17 @@ def _flatten(L): return ret def matchPreviousLiteral(expr): - """Helper to define an expression that is indirectly defined from - the tokens matched in a previous expression, that is, it looks - for a 'repeat' of a previous expression. For example:: - first = Word(nums) - second = matchPreviousLiteral(first) - matchExpr = first + ":" + second - will match C{"1:1"}, but not C{"1:2"}. Because this matches a - previous literal, will also match the leading C{"1:1"} in C{"1:10"}. - If this is not desired, use C{matchPreviousExpr}. - Do *not* use with packrat parsing enabled. + """ + Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks + for a 'repeat' of a previous expression. For example:: + first = Word(nums) + second = matchPreviousLiteral(first) + matchExpr = first + ":" + second + will match C{"1:1"}, but not C{"1:2"}. Because this matches a + previous literal, will also match the leading C{"1:1"} in C{"1:10"}. + If this is not desired, use C{matchPreviousExpr}. + Do I{not} use with packrat parsing enabled. """ rep = Forward() def copyTokenToRepeater(s,l,t): @@ -3296,17 +4494,18 @@ def copyTokenToRepeater(s,l,t): return rep def matchPreviousExpr(expr): - """Helper to define an expression that is indirectly defined from - the tokens matched in a previous expression, that is, it looks - for a 'repeat' of a previous expression. For example:: - first = Word(nums) - second = matchPreviousExpr(first) - matchExpr = first + ":" + second - will match C{"1:1"}, but not C{"1:2"}. Because this matches by - expressions, will *not* match the leading C{"1:1"} in C{"1:10"}; - the expressions are evaluated first, and then compared, so - C{"1"} is compared with C{"10"}. - Do *not* use with packrat parsing enabled. + """ + Helper to define an expression that is indirectly defined from + the tokens matched in a previous expression, that is, it looks + for a 'repeat' of a previous expression. For example:: + first = Word(nums) + second = matchPreviousExpr(first) + matchExpr = first + ":" + second + will match C{"1:1"}, but not C{"1:2"}. Because this matches by + expressions, will I{not} match the leading C{"1:1"} in C{"1:10"}; + the expressions are evaluated first, and then compared, so + C{"1"} is compared with C{"10"}. + Do I{not} use with packrat parsing enabled. """ rep = Forward() e2 = expr.copy() @@ -3331,16 +4530,27 @@ def _escapeRegexRangeChars(s): return _ustr(s) def oneOf( strs, caseless=False, useRegex=True ): - """Helper to quickly define a set of alternative Literals, and makes sure to do - longest-first testing when there is a conflict, regardless of the input order, - but returns a C{L{MatchFirst}} for best performance. - - Parameters: - - strs - a string of space-delimited literals, or a list of string literals - - caseless - (default=False) - treat all literals as caseless - - useRegex - (default=True) - as an optimization, will generate a Regex + """ + Helper to quickly define a set of alternative Literals, and makes sure to do + longest-first testing when there is a conflict, regardless of the input order, + but returns a C{L{MatchFirst}} for best performance. + + Parameters: + - strs - a string of space-delimited literals, or a collection of string literals + - caseless - (default=C{False}) - treat all literals as caseless + - useRegex - (default=C{True}) - as an optimization, will generate a Regex object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or if creating a C{Regex} raises an exception) + + Example:: + comp_oper = oneOf("< = > <= >= !=") + var = Word(alphas) + number = Word(nums) + term = var | number + comparison_expr = term + comp_oper + term + print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12")) + prints:: + [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']] """ if caseless: isequal = ( lambda a,b: a.upper() == b.upper() ) @@ -3354,12 +4564,10 @@ def oneOf( strs, caseless=False, useRegex=True ): symbols = [] if isinstance(strs,basestring): symbols = strs.split() - elif isinstance(strs, collections.Sequence): - symbols = list(strs[:]) - elif isinstance(strs, _generatorType): + elif isinstance(strs, collections.Iterable): symbols = list(strs) else: - warnings.warn("Invalid argument to oneOf, expected string or list", + warnings.warn("Invalid argument to oneOf, expected string or iterable", SyntaxWarning, stacklevel=2) if not symbols: return NoMatch() @@ -3386,7 +4594,7 @@ def oneOf( strs, caseless=False, useRegex=True ): return Regex( "[%s]" % "".join(_escapeRegexRangeChars(sym) for sym in symbols) ).setName(' | '.join(symbols)) else: return Regex( "|".join(re.escape(sym) for sym in symbols) ).setName(' | '.join(symbols)) - except: + except Exception: warnings.warn("Exception creating Regex for oneOf, building MatchFirst", SyntaxWarning, stacklevel=2) @@ -3395,27 +4603,64 @@ def oneOf( strs, caseless=False, useRegex=True ): return MatchFirst(parseElementClass(sym) for sym in symbols).setName(' | '.join(symbols)) def dictOf( key, value ): - """Helper to easily and clearly define a dictionary by specifying the respective patterns - for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens - in the proper order. The key pattern can include delimiting markers or punctuation, - as long as they are suppressed, thereby leaving the significant key text. The value - pattern can include named results, so that the C{Dict} results can include named token - fields. + """ + Helper to easily and clearly define a dictionary by specifying the respective patterns + for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens + in the proper order. The key pattern can include delimiting markers or punctuation, + as long as they are suppressed, thereby leaving the significant key text. The value + pattern can include named results, so that the C{Dict} results can include named token + fields. + + Example:: + text = "shape: SQUARE posn: upper left color: light blue texture: burlap" + attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) + print(OneOrMore(attr_expr).parseString(text).dump()) + + attr_label = label + attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) + + # similar to Dict, but simpler call format + result = dictOf(attr_label, attr_value).parseString(text) + print(result.dump()) + print(result['shape']) + print(result.shape) # object attribute access works too + print(result.asDict()) + prints:: + [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] + - color: light blue + - posn: upper left + - shape: SQUARE + - texture: burlap + SQUARE + SQUARE + {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} """ return Dict( ZeroOrMore( Group ( key + value ) ) ) def originalTextFor(expr, asString=True): - """Helper to return the original, untokenized text for a given expression. Useful to - restore the parsed fields of an HTML start tag into the raw tag text itself, or to - revert separate tokens with intervening whitespace back to the original matching - input text. By default, returns astring containing the original parsed text. + """ + Helper to return the original, untokenized text for a given expression. Useful to + restore the parsed fields of an HTML start tag into the raw tag text itself, or to + revert separate tokens with intervening whitespace back to the original matching + input text. By default, returns astring containing the original parsed text. - If the optional C{asString} argument is passed as C{False}, then the return value is a - C{L{ParseResults}} containing any results names that were originally matched, and a - single token containing the original matched text from the input string. So if - the expression passed to C{L{originalTextFor}} contains expressions with defined - results names, you must set C{asString} to C{False} if you want to preserve those - results name values.""" + If the optional C{asString} argument is passed as C{False}, then the return value is a + C{L{ParseResults}} containing any results names that were originally matched, and a + single token containing the original matched text from the input string. So if + the expression passed to C{L{originalTextFor}} contains expressions with defined + results names, you must set C{asString} to C{False} if you want to preserve those + results name values. + + Example:: + src = "this is test <b> bold <i>text</i> </b> normal text " + for tag in ("b","i"): + opener,closer = makeHTMLTags(tag) + patt = originalTextFor(opener + SkipTo(closer) + closer) + print(patt.searchString(src)[0]) + prints:: + ['<b> bold <i>text</i> </b>'] + ['<i>text</i>'] + """ locMarker = Empty().setParseAction(lambda s,loc,t: loc) endlocMarker = locMarker.copy() endlocMarker.callPreparse = False @@ -3426,22 +4671,35 @@ def originalTextFor(expr, asString=True): def extractText(s,l,t): t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]] matchExpr.setParseAction(extractText) + matchExpr.ignoreExprs = expr.ignoreExprs return matchExpr def ungroup(expr): - """Helper to undo pyparsing's default grouping of And expressions, even - if all but one are non-empty.""" + """ + Helper to undo pyparsing's default grouping of And expressions, even + if all but one are non-empty. + """ return TokenConverter(expr).setParseAction(lambda t:t[0]) def locatedExpr(expr): - """Helper to decorate a returned token with its starting and ending locations in the input string. - This helper adds the following results names: - - locn_start = location where matched expression begins - - locn_end = location where matched expression ends - - value = the actual parsed results - - Be careful if the input text contains C{<TAB>} characters, you may want to call - C{L{ParserElement.parseWithTabs}} + """ + Helper to decorate a returned token with its starting and ending locations in the input string. + This helper adds the following results names: + - locn_start = location where matched expression begins + - locn_end = location where matched expression ends + - value = the actual parsed results + + Be careful if the input text contains C{<TAB>} characters, you may want to call + C{L{ParserElement.parseWithTabs}} + + Example:: + wd = Word(alphas) + for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"): + print(match) + prints:: + [[0, 'ljsdf', 5]] + [[8, 'lksdjjf', 15]] + [[18, 'lkkjj', 23]] """ locator = Empty().setParseAction(lambda s,l,t: l) return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end")) @@ -3462,31 +4720,33 @@ def locatedExpr(expr): _reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]" def srange(s): - r"""Helper to easily define string ranges for use in Word construction. Borrows - syntax from regexp '[]' string range definitions:: - srange("[0-9]") -> "0123456789" - srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" - srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" - The input string must be enclosed in []'s, and the returned string is the expanded - character set joined into a single string. - The values enclosed in the []'s may be:: - a single character - an escaped character with a leading backslash (such as \- or \]) - an escaped hex character with a leading '\x' (\x21, which is a '!' character) - (\0x## is also supported for backwards compatibility) - an escaped octal character with a leading '\0' (\041, which is a '!' character) - a range of any of the above, separated by a dash ('a-z', etc.) - any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.) + r""" + Helper to easily define string ranges for use in Word construction. Borrows + syntax from regexp '[]' string range definitions:: + srange("[0-9]") -> "0123456789" + srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" + srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" + The input string must be enclosed in []'s, and the returned string is the expanded + character set joined into a single string. + The values enclosed in the []'s may be: + - a single character + - an escaped character with a leading backslash (such as C{\-} or C{\]}) + - an escaped hex character with a leading C{'\x'} (C{\x21}, which is a C{'!'} character) + (C{\0x##} is also supported for backwards compatibility) + - an escaped octal character with a leading C{'\0'} (C{\041}, which is a C{'!'} character) + - a range of any of the above, separated by a dash (C{'a-z'}, etc.) + - any combination of the above (C{'aeiouy'}, C{'a-zA-Z0-9_$'}, etc.) """ _expanded = lambda p: p if not isinstance(p,ParseResults) else ''.join(unichr(c) for c in range(ord(p[0]),ord(p[1])+1)) try: return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body) - except: + except Exception: return "" def matchOnlyAtCol(n): - """Helper method for defining parse actions that require matching at a specific - column in the input text. + """ + Helper method for defining parse actions that require matching at a specific + column in the input text. """ def verifyCol(strg,locn,toks): if col(locn,strg) != n: @@ -3494,26 +4754,83 @@ def verifyCol(strg,locn,toks): return verifyCol def replaceWith(replStr): - """Helper method for common parse actions that simply return a literal value. Especially - useful when used with C{L{transformString<ParserElement.transformString>}()}. + """ + Helper method for common parse actions that simply return a literal value. Especially + useful when used with C{L{transformString<ParserElement.transformString>}()}. + + Example:: + num = Word(nums).setParseAction(lambda toks: int(toks[0])) + na = oneOf("N/A NA").setParseAction(replaceWith(math.nan)) + term = na | num + + OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234] """ return lambda s,l,t: [replStr] def removeQuotes(s,l,t): - """Helper parse action for removing quotation marks from parsed quoted strings. - To use, add this parse action to quoted string using:: - quotedString.setParseAction( removeQuotes ) + """ + Helper parse action for removing quotation marks from parsed quoted strings. + + Example:: + # by default, quotation marks are included in parsed results + quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] + + # use removeQuotes to strip quotation marks from parsed results + quotedString.setParseAction(removeQuotes) + quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] """ return t[0][1:-1] -def upcaseTokens(s,l,t): - """Helper parse action to convert tokens to upper case.""" - return [ tt.upper() for tt in map(_ustr,t) ] +def tokenMap(func, *args): + """ + Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional + args are passed, they are forwarded to the given function as additional arguments after + the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the + parsed data to an integer using base 16. + + Example (compare the last to example in L{ParserElement.transformString}:: + hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16)) + hex_ints.runTests(''' + 00 11 22 aa FF 0a 0d 1a + ''') + + upperword = Word(alphas).setParseAction(tokenMap(str.upper)) + OneOrMore(upperword).runTests(''' + my kingdom for a horse + ''') + + wd = Word(alphas).setParseAction(tokenMap(str.title)) + OneOrMore(wd).setParseAction(' '.join).runTests(''' + now is the winter of our discontent made glorious summer by this sun of york + ''') + prints:: + 00 11 22 aa FF 0a 0d 1a + [0, 17, 34, 170, 255, 10, 13, 26] + + my kingdom for a horse + ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE'] + + now is the winter of our discontent made glorious summer by this sun of york + ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York'] + """ + def pa(s,l,t): + return [func(tokn, *args) for tokn in t] + + try: + func_name = getattr(func, '__name__', + getattr(func, '__class__').__name__) + except Exception: + func_name = str(func) + pa.__name__ = func_name + + return pa -def downcaseTokens(s,l,t): - """Helper parse action to convert tokens to lower case.""" - return [ tt.lower() for tt in map(_ustr,t) ] +upcaseTokens = tokenMap(lambda t: _ustr(t).upper()) +"""(Deprecated) Helper parse action to convert tokens to upper case. Deprecated in favor of L{pyparsing_common.upcaseTokens}""" +downcaseTokens = tokenMap(lambda t: _ustr(t).lower()) +"""(Deprecated) Helper parse action to convert tokens to lower case. Deprecated in favor of L{pyparsing_common.downcaseTokens}""" + def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" if isinstance(tagStr,basestring): @@ -3544,33 +4861,83 @@ def _makeTags(tagStr, xml): return openTag, closeTag def makeHTMLTags(tagStr): - """Helper to construct opening and closing tag expressions for HTML, given a tag name""" + """ + Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches + tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. + + Example:: + text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>' + # makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple + a,a_end = makeHTMLTags("A") + link_expr = a + SkipTo(a_end)("link_text") + a_end + + for link in link_expr.searchString(text): + # attributes in the <A> tag (like "href" shown here) are also accessible as named results + print(link.link_text, '->', link.href) + prints:: + pyparsing -> http://pyparsing.wikispaces.com + """ return _makeTags( tagStr, False ) def makeXMLTags(tagStr): - """Helper to construct opening and closing tag expressions for XML, given a tag name""" + """ + Helper to construct opening and closing tag expressions for XML, given a tag name. Matches + tags only in the given upper/lower case. + + Example: similar to L{makeHTMLTags} + """ return _makeTags( tagStr, True ) def withAttribute(*args,**attrDict): - """Helper to create a validating parse action to be used with start tags created - with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag - with a required attribute value, to avoid false matches on common tags such as - C{<TD>} or C{<DIV>}. - - Call C{withAttribute} with a series of attribute names and values. Specify the list - of filter attributes names and values as: - - keyword arguments, as in C{(align="right")}, or - - as an explicit dict with C{**} operator, when an attribute name is also a Python + """ + Helper to create a validating parse action to be used with start tags created + with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag + with a required attribute value, to avoid false matches on common tags such as + C{<TD>} or C{<DIV>}. + + Call C{withAttribute} with a series of attribute names and values. Specify the list + of filter attributes names and values as: + - keyword arguments, as in C{(align="right")}, or + - as an explicit dict with C{**} operator, when an attribute name is also a Python reserved word, as in C{**{"class":"Customer", "align":"right"}} - - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") ) - For attribute names with a namespace prefix, you must use the second form. Attribute - names are matched insensitive to upper/lower case. + - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") ) + For attribute names with a namespace prefix, you must use the second form. Attribute + names are matched insensitive to upper/lower case. - If just testing for C{class} (with or without a namespace), use C{L{withClass}}. - - To verify that the attribute exists, but without specifying a value, pass - C{withAttribute.ANY_VALUE} as the value. - """ + If just testing for C{class} (with or without a namespace), use C{L{withClass}}. + + To verify that the attribute exists, but without specifying a value, pass + C{withAttribute.ANY_VALUE} as the value. + + Example:: + html = ''' + <div> + Some text + <div type="grid">1 4 0 1 0</div> + <div type="graph">1,3 2,3 1,1</div> + <div>this has no type</div> + </div> + + ''' + div,div_end = makeHTMLTags("div") + + # only match div tag having a type attribute with value "grid" + div_grid = div().setParseAction(withAttribute(type="grid")) + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.searchString(html): + print(grid_header.body) + + # construct a match with any div tag having a type attribute, regardless of the value + div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE)) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.searchString(html): + print(div_header.body) + prints:: + 1 4 0 1 0 + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ if args: attrs = args[:] else: @@ -3587,9 +4954,37 @@ def pa(s,l,tokens): withAttribute.ANY_VALUE = object() def withClass(classname, namespace=''): - """Simplified version of C{L{withAttribute}} when matching on a div class - made - difficult because C{class} is a reserved word in Python. - """ + """ + Simplified version of C{L{withAttribute}} when matching on a div class - made + difficult because C{class} is a reserved word in Python. + + Example:: + html = ''' + <div> + Some text + <div class="grid">1 4 0 1 0</div> + <div class="graph">1,3 2,3 1,1</div> + <div>this &lt;div&gt; has no class</div> + </div> + + ''' + div,div_end = makeHTMLTags("div") + div_grid = div().setParseAction(withClass("grid")) + + grid_expr = div_grid + SkipTo(div | div_end)("body") + for grid_header in grid_expr.searchString(html): + print(grid_header.body) + + div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE)) + div_expr = div_any_type + SkipTo(div | div_end)("body") + for div_header in div_expr.searchString(html): + print(div_header.body) + prints:: + 1 4 0 1 0 + + 1 4 0 1 0 + 1,3 2,3 1,1 + """ classattr = "%s:class" % namespace if namespace else "class" return withAttribute(**{classattr : classname}) @@ -3598,30 +4993,63 @@ def withClass(classname, namespace=''): opAssoc.RIGHT = object() def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ): - """Helper method for constructing grammars of expressions made up of - operators working in a precedence hierarchy. Operators may be unary or - binary, left- or right-associative. Parse actions can also be attached - to operator expressions. - - Parameters: - - baseExpr - expression representing the most basic element for the nested - - opList - list of tuples, one for each operator precedence level in the - expression grammar; each tuple is of the form - (opExpr, numTerms, rightLeftAssoc, parseAction), where: - - opExpr is the pyparsing expression for the operator; - may also be a string, which will be converted to a Literal; - if numTerms is 3, opExpr is a tuple of two expressions, for the - two operators separating the 3 terms - - numTerms is the number of terms for this operator (must - be 1, 2, or 3) - - rightLeftAssoc is the indicator whether the operator is - right or left associative, using the pyparsing-defined - constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}. - - parseAction is the parse action to be associated with - expressions matching this operator expression (the - parse action tuple member may be omitted) - - lpar - expression for matching left-parentheses (default=Suppress('(')) - - rpar - expression for matching right-parentheses (default=Suppress(')')) + """ + Helper method for constructing grammars of expressions made up of + operators working in a precedence hierarchy. Operators may be unary or + binary, left- or right-associative. Parse actions can also be attached + to operator expressions. The generated parser will also recognize the use + of parentheses to override operator precedences (see example below). + + Note: if you define a deep operator list, you may see performance issues + when using infixNotation. See L{ParserElement.enablePackrat} for a + mechanism to potentially improve your parser performance. + + Parameters: + - baseExpr - expression representing the most basic element for the nested + - opList - list of tuples, one for each operator precedence level in the + expression grammar; each tuple is of the form + (opExpr, numTerms, rightLeftAssoc, parseAction), where: + - opExpr is the pyparsing expression for the operator; + may also be a string, which will be converted to a Literal; + if numTerms is 3, opExpr is a tuple of two expressions, for the + two operators separating the 3 terms + - numTerms is the number of terms for this operator (must + be 1, 2, or 3) + - rightLeftAssoc is the indicator whether the operator is + right or left associative, using the pyparsing-defined + constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}. + - parseAction is the parse action to be associated with + expressions matching this operator expression (the + parse action tuple member may be omitted) + - lpar - expression for matching left-parentheses (default=C{Suppress('(')}) + - rpar - expression for matching right-parentheses (default=C{Suppress(')')}) + + Example:: + # simple example of four-function arithmetic with ints and variable names + integer = pyparsing_common.signed_integer + varname = pyparsing_common.identifier + + arith_expr = infixNotation(integer | varname, + [ + ('-', 1, opAssoc.RIGHT), + (oneOf('* /'), 2, opAssoc.LEFT), + (oneOf('+ -'), 2, opAssoc.LEFT), + ]) + + arith_expr.runTests(''' + 5+3*6 + (5+3)*6 + -2--11 + ''', fullDump=False) + prints:: + 5+3*6 + [[5, '+', [3, '*', 6]]] + + (5+3)*6 + [[[5, '+', 3], '*', 6]] + + -2--11 + [[['-', 2], '-', ['-', 11]]] """ ret = Forward() lastExpr = baseExpr | ( lpar + ret + rpar ) @@ -3670,33 +5098,73 @@ def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ): lastExpr = thisExpr ret <<= lastExpr return ret + operatorPrecedence = infixNotation +"""(Deprecated) Former name of C{L{infixNotation}}, will be dropped in a future release.""" -dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*"').setName("string enclosed in double quotes") -sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*'").setName("string enclosed in single quotes") -quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*')''').setName("quotedString using single or double quotes") +dblQuotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*')+'"').setName("string enclosed in double quotes") +sglQuotedString = Combine(Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*")+"'").setName("string enclosed in single quotes") +quotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*')+'"'| + Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*")+"'").setName("quotedString using single or double quotes") unicodeString = Combine(_L('u') + quotedString.copy()).setName("unicode string literal") def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()): - """Helper method for defining nested lists enclosed in opening and closing - delimiters ("(" and ")" are the default). - - Parameters: - - opener - opening character for a nested list (default="("); can also be a pyparsing expression - - closer - closing character for a nested list (default=")"); can also be a pyparsing expression - - content - expression for items within the nested lists (default=None) - - ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString) - - If an expression is not provided for the content argument, the nested - expression will capture all whitespace-delimited content between delimiters - as a list of separate values. - - Use the C{ignoreExpr} argument to define expressions that may contain - opening or closing characters that should not be treated as opening - or closing characters for nesting, such as quotedString or a comment - expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}. - The default is L{quotedString}, but if no expressions are to be ignored, - then pass C{None} for this argument. + """ + Helper method for defining nested lists enclosed in opening and closing + delimiters ("(" and ")" are the default). + + Parameters: + - opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression + - closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression + - content - expression for items within the nested lists (default=C{None}) + - ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString}) + + If an expression is not provided for the content argument, the nested + expression will capture all whitespace-delimited content between delimiters + as a list of separate values. + + Use the C{ignoreExpr} argument to define expressions that may contain + opening or closing characters that should not be treated as opening + or closing characters for nesting, such as quotedString or a comment + expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}. + The default is L{quotedString}, but if no expressions are to be ignored, + then pass C{None} for this argument. + + Example:: + data_type = oneOf("void int short long char float double") + decl_data_type = Combine(data_type + Optional(Word('*'))) + ident = Word(alphas+'_', alphanums+'_') + number = pyparsing_common.number + arg = Group(decl_data_type + ident) + LPAR,RPAR = map(Suppress, "()") + + code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment)) + + c_function = (decl_data_type("type") + + ident("name") + + LPAR + Optional(delimitedList(arg), [])("args") + RPAR + + code_body("body")) + c_function.ignore(cStyleComment) + + source_code = ''' + int is_odd(int x) { + return (x%2); + } + + int dec_to_hex(char hchar) { + if (hchar >= '0' && hchar <= '9') { + return (ord(hchar)-ord('0')); + } else { + return (10+ord(hchar)-ord('A')); + } + } + ''' + for func in c_function.searchString(source_code): + print("%(name)s (%(type)s) args: %(args)s" % func) + + prints:: + is_odd (int) args: [['int', 'x']] + dec_to_hex (int) args: [['char', 'hchar']] """ if opener == closer: raise ValueError("opening and closing strings cannot be the same") @@ -3731,20 +5199,82 @@ def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.cop return ret def indentedBlock(blockStatementExpr, indentStack, indent=True): - """Helper method for defining space-delimited indentation blocks, such as - those used to define block statements in Python source code. + """ + Helper method for defining space-delimited indentation blocks, such as + those used to define block statements in Python source code. - Parameters: - - blockStatementExpr - expression defining syntax of statement that + Parameters: + - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - - indentStack - list created by caller to manage indentation stack + - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - - indent - boolean indicating whether block must be indented beyond the + - indent - boolean indicating whether block must be indented beyond the the current level; set to False for block of left-most statements - (default=True) - - A valid block must contain at least one C{blockStatement}. + (default=C{True}) + + A valid block must contain at least one C{blockStatement}. + + Example:: + data = ''' + def A(z): + A1 + B = 100 + G = A2 + A2 + A3 + B + def BB(a,b,c): + BB1 + def BBA(): + bba1 + bba2 + bba3 + C + D + def spam(x,y): + def eggs(z): + pass + ''' + + + indentStack = [1] + stmt = Forward() + + identifier = Word(alphas, alphanums) + funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":") + func_body = indentedBlock(stmt, indentStack) + funcDef = Group( funcDecl + func_body ) + + rvalue = Forward() + funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") + rvalue << (funcCall | identifier | Word(nums)) + assignment = Group(identifier + "=" + rvalue) + stmt << ( funcDef | assignment | identifier ) + + module_body = OneOrMore(stmt) + + parseTree = module_body.parseString(data) + parseTree.pprint() + prints:: + [['def', + 'A', + ['(', 'z', ')'], + ':', + [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], + 'B', + ['def', + 'BB', + ['(', 'a', 'b', 'c', ')'], + ':', + [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], + 'C', + 'D', + ['def', + 'spam', + ['(', 'x', 'y', ')'], + ':', + [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] """ def checkPeerIndent(s,l,t): if l >= len(s): return @@ -3793,45 +5323,374 @@ def replaceHTMLEntity(t): return _htmlEntityMap.get(t.entity) # it's easy to get these comment structures wrong - they're very common, so may as well make them available -cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment") +cStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/').setName("C style comment") +"Comment of the form C{/* ... */}" htmlComment = Regex(r"<!--[\s\S]*?-->").setName("HTML comment") +"Comment of the form C{<!-- ... -->}" + restOfLine = Regex(r".*").leaveWhitespace().setName("rest of line") -dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment") -cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?<!\\)|\Z))").setName("C++ style comment") +dblSlashComment = Regex(r"//(?:\\\n|[^\n])*").setName("// comment") +"Comment of the form C{// ... (to end of line)}" + +cppStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/'| dblSlashComment).setName("C++ style comment") +"Comment of either form C{L{cStyleComment}} or C{L{dblSlashComment}}" javaStyleComment = cppStyleComment +"Same as C{L{cppStyleComment}}" + pythonStyleComment = Regex(r"#.*").setName("Python style comment") +"Comment of the form C{# ... (to end of line)}" + _commasepitem = Combine(OneOrMore(Word(printables, excludeChars=',') + Optional( Word(" \t") + ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem") commaSeparatedList = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("commaSeparatedList") +"""(Deprecated) Predefined expression of 1 or more printable words or quoted strings, separated by commas. + This expression is deprecated in favor of L{pyparsing_common.comma_separated_list}.""" + +# some other useful expressions - using lower-case class name since we are really using this as a namespace +class pyparsing_common: + """ + Here are some common low-level expressions that may be useful in jump-starting parser development: + - numeric forms (L{integers<integer>}, L{reals<real>}, L{scientific notation<sci_real>}) + - common L{programming identifiers<identifier>} + - network addresses (L{MAC<mac_address>}, L{IPv4<ipv4_address>}, L{IPv6<ipv6_address>}) + - ISO8601 L{dates<iso8601_date>} and L{datetime<iso8601_datetime>} + - L{UUID<uuid>} + - L{comma-separated list<comma_separated_list>} + Parse actions: + - C{L{convertToInteger}} + - C{L{convertToFloat}} + - C{L{convertToDate}} + - C{L{convertToDatetime}} + - C{L{stripHTMLTags}} + - C{L{upcaseTokens}} + - C{L{downcaseTokens}} + + Example:: + pyparsing_common.number.runTests(''' + # any int or real number, returned as the appropriate type + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + pyparsing_common.fnumber.runTests(''' + # any int or real number, returned as float + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + ''') + + pyparsing_common.hex_integer.runTests(''' + # hex numbers + 100 + FF + ''') + + pyparsing_common.fraction.runTests(''' + # fractions + 1/2 + -3/4 + ''') + + pyparsing_common.mixed_integer.runTests(''' + # mixed fractions + 1 + 1/2 + -3/4 + 1-3/4 + ''') + + import uuid + pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) + pyparsing_common.uuid.runTests(''' + # uuid + 12345678-1234-5678-1234-567812345678 + ''') + prints:: + # any int or real number, returned as the appropriate type + 100 + [100] + + -100 + [-100] + + +100 + [100] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + # any int or real number, returned as float + 100 + [100.0] + + -100 + [-100.0] + + +100 + [100.0] + + 3.14159 + [3.14159] + + 6.02e23 + [6.02e+23] + + 1e-12 + [1e-12] + + # hex numbers + 100 + [256] + + FF + [255] + + # fractions + 1/2 + [0.5] + + -3/4 + [-0.75] + + # mixed fractions + 1 + [1] + + 1/2 + [0.5] + + -3/4 + [-0.75] + + 1-3/4 + [1.75] + + # uuid + 12345678-1234-5678-1234-567812345678 + [UUID('12345678-1234-5678-1234-567812345678')] + """ + + convertToInteger = tokenMap(int) + """ + Parse action for converting parsed integers to Python int + """ + + convertToFloat = tokenMap(float) + """ + Parse action for converting parsed numbers to Python float + """ + + integer = Word(nums).setName("integer").setParseAction(convertToInteger) + """expression that parses an unsigned integer, returns an int""" + + hex_integer = Word(hexnums).setName("hex integer").setParseAction(tokenMap(int,16)) + """expression that parses a hexadecimal integer, returns an int""" + + signed_integer = Regex(r'[+-]?\d+').setName("signed integer").setParseAction(convertToInteger) + """expression that parses an integer with optional leading sign, returns an int""" + + fraction = (signed_integer().setParseAction(convertToFloat) + '/' + signed_integer().setParseAction(convertToFloat)).setName("fraction") + """fractional expression of an integer divided by an integer, returns a float""" + fraction.addParseAction(lambda t: t[0]/t[-1]) + + mixed_integer = (fraction | signed_integer + Optional(Optional('-').suppress() + fraction)).setName("fraction or mixed integer-fraction") + """mixed integer of the form 'integer - fraction', with optional leading integer, returns float""" + mixed_integer.addParseAction(sum) + + real = Regex(r'[+-]?\d+\.\d*').setName("real number").setParseAction(convertToFloat) + """expression that parses a floating point number and returns a float""" + + sci_real = Regex(r'[+-]?\d+([eE][+-]?\d+|\.\d*([eE][+-]?\d+)?)').setName("real number with scientific notation").setParseAction(convertToFloat) + """expression that parses a floating point number with optional scientific notation and returns a float""" + + # streamlining this expression makes the docs nicer-looking + number = (sci_real | real | signed_integer).streamline() + """any numeric expression, returns the corresponding Python type""" + + fnumber = Regex(r'[+-]?\d+\.?\d*([eE][+-]?\d+)?').setName("fnumber").setParseAction(convertToFloat) + """any int or real number, returned as float""" + + identifier = Word(alphas+'_', alphanums+'_').setName("identifier") + """typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')""" + + ipv4_address = Regex(r'(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}').setName("IPv4 address") + "IPv4 address (C{0.0.0.0 - 255.255.255.255})" + + _ipv6_part = Regex(r'[0-9a-fA-F]{1,4}').setName("hex_integer") + _full_ipv6_address = (_ipv6_part + (':' + _ipv6_part)*7).setName("full IPv6 address") + _short_ipv6_address = (Optional(_ipv6_part + (':' + _ipv6_part)*(0,6)) + "::" + Optional(_ipv6_part + (':' + _ipv6_part)*(0,6))).setName("short IPv6 address") + _short_ipv6_address.addCondition(lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8) + _mixed_ipv6_address = ("::ffff:" + ipv4_address).setName("mixed IPv6 address") + ipv6_address = Combine((_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).setName("IPv6 address")).setName("IPv6 address") + "IPv6 address (long, short, or mixed form)" + + mac_address = Regex(r'[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}').setName("MAC address") + "MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)" + + @staticmethod + def convertToDate(fmt="%Y-%m-%d"): + """ + Helper to create a parse action for converting parsed date string to Python datetime.date + + Params - + - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"}) + + Example:: + date_expr = pyparsing_common.iso8601_date.copy() + date_expr.setParseAction(pyparsing_common.convertToDate()) + print(date_expr.parseString("1999-12-31")) + prints:: + [datetime.date(1999, 12, 31)] + """ + def cvt_fn(s,l,t): + try: + return datetime.strptime(t[0], fmt).date() + except ValueError as ve: + raise ParseException(s, l, str(ve)) + return cvt_fn + + @staticmethod + def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"): + """ + Helper to create a parse action for converting parsed datetime string to Python datetime.datetime + + Params - + - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"}) + + Example:: + dt_expr = pyparsing_common.iso8601_datetime.copy() + dt_expr.setParseAction(pyparsing_common.convertToDatetime()) + print(dt_expr.parseString("1999-12-31T23:59:59.999")) + prints:: + [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)] + """ + def cvt_fn(s,l,t): + try: + return datetime.strptime(t[0], fmt) + except ValueError as ve: + raise ParseException(s, l, str(ve)) + return cvt_fn + + iso8601_date = Regex(r'(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?').setName("ISO8601 date") + "ISO8601 date (C{yyyy-mm-dd})" + + iso8601_datetime = Regex(r'(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)[T ](?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d(\.\d*)?)?)?(?P<tz>Z|[+-]\d\d:?\d\d)?').setName("ISO8601 datetime") + "ISO8601 datetime (C{yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)}) - trailing seconds, milliseconds, and timezone optional; accepts separating C{'T'} or C{' '}" + + uuid = Regex(r'[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}').setName("UUID") + "UUID (C{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx})" + + _html_stripper = anyOpenTag.suppress() | anyCloseTag.suppress() + @staticmethod + def stripHTMLTags(s, l, tokens): + """ + Parse action to remove HTML tags from web page HTML source + + Example:: + # strip HTML links from normal text + text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>' + td,td_end = makeHTMLTags("TD") + table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end + + print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page' + """ + return pyparsing_common._html_stripper.transformString(tokens[0]) + + _commasepitem = Combine(OneOrMore(~Literal(",") + ~LineEnd() + Word(printables, excludeChars=',') + + Optional( White(" \t") ) ) ).streamline().setName("commaItem") + comma_separated_list = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("comma separated list") + """Predefined expression of 1 or more printable words or quoted strings, separated by commas.""" + + upcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).upper())) + """Parse action to convert tokens to upper case.""" + + downcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).lower())) + """Parse action to convert tokens to lower case.""" if __name__ == "__main__": - selectToken = CaselessLiteral( "select" ) - fromToken = CaselessLiteral( "from" ) - - ident = Word( alphas, alphanums + "_$" ) - columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens ) - columnNameList = Group( delimitedList( columnName ) ).setName("columns") - tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens ) - tableNameList = Group( delimitedList( tableName ) ).setName("tables") - simpleSQL = ( selectToken + \ - ( '*' | columnNameList ).setResultsName( "columns" ) + \ - fromToken + \ - tableNameList.setResultsName( "tables" ) ) - - simpleSQL.runTests("""\ - SELECT * from XYZZY, ABC - select * from SYS.XYZZY - Select A from Sys.dual - Select AA,BB,CC from Sys.dual - Select A, B, C from Sys.dual - Select A, B, C from Sys.dual - Xelect A, B, C from Sys.dual - Select A, B, C frox Sys.dual - Select - Select ^^^ frox Sys.dual - Select A, B, C from Sys.dual, Table2""") + selectToken = CaselessLiteral("select") + fromToken = CaselessLiteral("from") + + ident = Word(alphas, alphanums + "_$") + + columnName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens) + columnNameList = Group(delimitedList(columnName)).setName("columns") + columnSpec = ('*' | columnNameList) + + tableName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens) + tableNameList = Group(delimitedList(tableName)).setName("tables") + + simpleSQL = selectToken("command") + columnSpec("columns") + fromToken + tableNameList("tables") + + # demo runTests method, including embedded comments in test string + simpleSQL.runTests(""" + # '*' as column list and dotted table name + select * from SYS.XYZZY + + # caseless match on "SELECT", and casts back to "select" + SELECT * from XYZZY, ABC + + # list of column names, and mixed case SELECT keyword + Select AA,BB,CC from Sys.dual + + # multiple tables + Select A, B, C from Sys.dual, Table2 + + # invalid SELECT keyword - should fail + Xelect A, B, C from Sys.dual + + # incomplete command - should fail + Select + + # invalid column name - should fail + Select ^^^ frox Sys.dual + + """) + + pyparsing_common.number.runTests(""" + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + """) + + # any int or real number, returned as float + pyparsing_common.fnumber.runTests(""" + 100 + -100 + +100 + 3.14159 + 6.02e23 + 1e-12 + """) + + pyparsing_common.hex_integer.runTests(""" + 100 + FF + """) + + import uuid + pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID)) + pyparsing_common.uuid.runTests(""" + 12345678-1234-5678-1234-567812345678 + """) diff --git a/pip/_vendor/requests/__init__.py b/pip/_vendor/requests/__init__.py --- a/pip/_vendor/requests/__init__.py +++ b/pip/_vendor/requests/__init__.py @@ -38,12 +38,11 @@ :copyright: (c) 2016 by Kenneth Reitz. :license: Apache 2.0, see LICENSE for more details. - """ __title__ = 'requests' -__version__ = '2.10.0' -__build__ = 0x021000 +__version__ = '2.11.1' +__build__ = 0x021101 __author__ = 'Kenneth Reitz' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2016 Kenneth Reitz' @@ -85,7 +84,5 @@ def emit(self, record): logging.getLogger(__name__).addHandler(NullHandler()) -import warnings - # FileModeWarnings go off per the default. warnings.simplefilter('default', FileModeWarning, append=True) diff --git a/pip/_vendor/requests/adapters.py b/pip/_vendor/requests/adapters.py --- a/pip/_vendor/requests/adapters.py +++ b/pip/_vendor/requests/adapters.py @@ -54,10 +54,24 @@ class BaseAdapter(object): def __init__(self): super(BaseAdapter, self).__init__() - def send(self): + def send(self, request, stream=False, timeout=None, verify=True, + cert=None, proxies=None): + """Sends PreparedRequest object. Returns Response object. + + :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. + :param stream: (optional) Whether to stream the request content. + :param timeout: (optional) How long to wait for the server to send + data before giving up, as a float, or a :ref:`(connect timeout, + read timeout) <timeouts>` tuple. + :type timeout: float or tuple + :param verify: (optional) Whether to verify SSL certificates. + :param cert: (optional) Any user-provided SSL certificate to be trusted. + :param proxies: (optional) The proxies dictionary to apply to the request. + """ raise NotImplementedError def close(self): + """Cleans up adapter specific items.""" raise NotImplementedError @@ -154,6 +168,7 @@ def proxy_manager_for(self, proxy, **proxy_kwargs): :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager. :returns: ProxyManager + :rtype: requests.packages.urllib3.ProxyManager """ if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] @@ -230,6 +245,7 @@ def build_response(self, req, resp): :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param resp: The urllib3 response object. + :rtype: requests.Response """ response = Response() @@ -265,6 +281,7 @@ def get_connection(self, url, proxies=None): :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. + :rtype: requests.packages.urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) @@ -302,6 +319,7 @@ def request_url(self, request, proxies): :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs. + :rtype: str """ proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme @@ -343,6 +361,7 @@ def proxy_headers(self, proxy): :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxies: The url of the proxy being used for this request. + :rtype: dict """ headers = {} username, password = get_auth_from_url(proxy) @@ -365,6 +384,7 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox :param verify: (optional) Whether to verify SSL certificates. :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. + :rtype: requests.Response """ conn = self.get_connection(request.url, proxies) diff --git a/pip/_vendor/requests/api.py b/pip/_vendor/requests/api.py --- a/pip/_vendor/requests/api.py +++ b/pip/_vendor/requests/api.py @@ -8,7 +8,6 @@ :copyright: (c) 2012 by Kenneth Reitz. :license: Apache2, see LICENSE for more details. - """ from . import sessions diff --git a/pip/_vendor/requests/auth.py b/pip/_vendor/requests/auth.py --- a/pip/_vendor/requests/auth.py +++ b/pip/_vendor/requests/auth.py @@ -43,6 +43,7 @@ def __call__(self, r): class HTTPBasicAuth(AuthBase): """Attaches HTTP Basic Authentication to the given Request object.""" + def __init__(self, username, password): self.username = username self.password = password @@ -63,6 +64,7 @@ def __call__(self, r): class HTTPProxyAuth(HTTPBasicAuth): """Attaches HTTP Proxy Authentication to a given Request object.""" + def __call__(self, r): r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password) return r @@ -70,6 +72,7 @@ def __call__(self, r): class HTTPDigestAuth(AuthBase): """Attaches HTTP Digest Authentication to the given Request object.""" + def __init__(self, username, password): self.username = username self.password = password @@ -87,6 +90,9 @@ def init_per_thread_state(self): self._thread_local.num_401_calls = None def build_digest_header(self, method, url): + """ + :rtype: str + """ realm = self._thread_local.chal['realm'] nonce = self._thread_local.chal['nonce'] @@ -179,7 +185,11 @@ def handle_redirect(self, r, **kwargs): self._thread_local.num_401_calls = 1 def handle_401(self, r, **kwargs): - """Takes the given response and tries digest-auth, if needed.""" + """ + Takes the given response and tries digest-auth, if needed. + + :rtype: requests.Response + """ if self._thread_local.pos is not None: # Rewind the file position indicator of the body to where diff --git a/pip/_vendor/requests/certs.py b/pip/_vendor/requests/certs.py --- a/pip/_vendor/requests/certs.py +++ b/pip/_vendor/requests/certs.py @@ -2,8 +2,8 @@ # -*- coding: utf-8 -*- """ -certs.py -~~~~~~~~ +requests.certs +~~~~~~~~~~~~~~ This module returns the preferred default CA certificate bundle. diff --git a/pip/_vendor/requests/compat.py b/pip/_vendor/requests/compat.py --- a/pip/_vendor/requests/compat.py +++ b/pip/_vendor/requests/compat.py @@ -1,7 +1,11 @@ # -*- coding: utf-8 -*- """ -pythoncompat +requests.compat +~~~~~~~~~~~~~~~ + +This module handles import compatibility issues between Python 2 and +Python 3. """ from .packages import chardet diff --git a/pip/_vendor/requests/cookies.py b/pip/_vendor/requests/cookies.py --- a/pip/_vendor/requests/cookies.py +++ b/pip/_vendor/requests/cookies.py @@ -1,6 +1,9 @@ # -*- coding: utf-8 -*- """ +requests.cookies +~~~~~~~~~~~~~~~~ + Compatibility code to be able to use `cookielib.CookieJar` with requests. requests.utils imports from here, so be careful with imports. @@ -131,7 +134,11 @@ def extract_cookies_to_jar(jar, request, response): def get_cookie_header(jar, request): - """Produce an appropriate Cookie header string to be sent with `request`, or None.""" + """ + Produce an appropriate Cookie header string to be sent with `request`, or None. + + :rtype: str + """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie') @@ -158,7 +165,8 @@ def remove_cookie_by_name(cookiejar, name, domain=None, path=None): class CookieConflictError(RuntimeError): """There are two cookies that meet the criteria specified in the cookie jar. - Use .get and .set and include domain and path args in order to be more specific.""" + Use .get and .set and include domain and path args in order to be more specific. + """ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): @@ -178,12 +186,14 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): .. warning:: dictionary operations that are normally O(1) may be O(n). """ + def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. - .. warning:: operation is O(n), not O(1).""" + .. warning:: operation is O(n), not O(1). + """ try: return self._find_no_duplicates(name, domain, path) except KeyError: @@ -192,7 +202,8 @@ def get(self, name, default=None, domain=None, path=None): def set(self, name, value, **kwargs): """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over - multiple domains.""" + multiple domains. + """ # support client code that unsets cookies by assignment of a None value: if value is None: remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path')) @@ -207,37 +218,54 @@ def set(self, name, value, **kwargs): def iterkeys(self): """Dict-like iterkeys() that returns an iterator of names of cookies - from the jar. See itervalues() and iteritems().""" + from the jar. + + .. seealso:: itervalues() and iteritems(). + """ for cookie in iter(self): yield cookie.name def keys(self): """Dict-like keys() that returns a list of names of cookies from the - jar. See values() and items().""" + jar. + + .. seealso:: values() and items(). + """ return list(self.iterkeys()) def itervalues(self): """Dict-like itervalues() that returns an iterator of values of cookies - from the jar. See iterkeys() and iteritems().""" + from the jar. + + .. seealso:: iterkeys() and iteritems(). + """ for cookie in iter(self): yield cookie.value def values(self): """Dict-like values() that returns a list of values of cookies from the - jar. See keys() and items().""" + jar. + + .. seealso:: keys() and items(). + """ return list(self.itervalues()) def iteritems(self): """Dict-like iteritems() that returns an iterator of name-value tuples - from the jar. See iterkeys() and itervalues().""" + from the jar. + + .. seealso:: iterkeys() and itervalues(). + """ for cookie in iter(self): yield cookie.name, cookie.value def items(self): """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.""" + jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a + vanilla python dict of key value pairs. + + .. seealso:: keys() and values(). + """ return list(self.iteritems()) def list_domains(self): @@ -258,7 +286,10 @@ def list_paths(self): def multiple_domains(self): """Returns True if there are multiple domains in the jar. - Returns False otherwise.""" + Returns False otherwise. + + :rtype: bool + """ domains = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: @@ -269,7 +300,10 @@ def multiple_domains(self): def get_dict(self, domain=None, path=None): """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the - requirements.""" + requirements. + + :rtype: dict + """ dictionary = {} for cookie in iter(self): if (domain is None or cookie.domain == domain) and (path is None @@ -288,20 +322,21 @@ def __getitem__(self, name): exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. - .. warning:: operation is O(n), not O(1).""" - + .. warning:: operation is O(n), not O(1). + """ return self._find_no_duplicates(name) def __setitem__(self, name, value): """Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that - case, use the more explicit set() method instead.""" - + case, use the more explicit set() method instead. + """ self.set(name, value) def __delitem__(self, name): """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s - ``remove_cookie_by_name()``.""" + ``remove_cookie_by_name()``. + """ remove_cookie_by_name(self, name) def set_cookie(self, cookie, *args, **kwargs): @@ -318,11 +353,17 @@ def update(self, other): super(RequestsCookieJar, self).update(other) def _find(self, name, domain=None, path=None): - """Requests uses this method internally to get cookie values. Takes as - args name and optional domain and path. Returns a cookie.value. If - there are conflicting cookies, _find arbitrarily chooses one. See - _find_no_duplicates if you want an exception thrown if there are - conflicting cookies.""" + """Requests uses this method internally to get cookie values. + + If there are conflicting cookies, _find arbitrarily chooses one. + See _find_no_duplicates if you want an exception thrown if there are + conflicting cookies. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :return: cookie.value + """ for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: @@ -333,10 +374,16 @@ def _find(self, name, domain=None, path=None): def _find_no_duplicates(self, name, domain=None, path=None): """Both ``__get_item__`` and ``get`` call this function: it's never - used elsewhere in Requests. Takes as args name and optional domain and - path. Returns a cookie.value. Throws KeyError if cookie is not found - and CookieConflictError if there are multiple cookies that match name - and optionally domain and path.""" + used elsewhere in Requests. + + :param name: a string containing name of cookie + :param domain: (optional) string containing domain of cookie + :param path: (optional) string containing path of cookie + :raises KeyError: if cookie is not found + :raises CookieConflictError: if there are multiple cookies + that match name and optionally domain and path + :return: cookie.value + """ toReturn = None for cookie in iter(self): if cookie.name == name: diff --git a/pip/_vendor/requests/exceptions.py b/pip/_vendor/requests/exceptions.py --- a/pip/_vendor/requests/exceptions.py +++ b/pip/_vendor/requests/exceptions.py @@ -5,19 +5,17 @@ ~~~~~~~~~~~~~~~~~~~ This module contains the set of Requests' exceptions. - """ from .packages.urllib3.exceptions import HTTPError as BaseHTTPError class RequestException(IOError): """There was an ambiguous exception that occurred while handling your - request.""" + request. + """ def __init__(self, *args, **kwargs): - """ - Initialize RequestException with `request` and `response` objects. - """ + """Initialize RequestException with `request` and `response` objects.""" response = kwargs.pop('response', None) self.response = response self.request = kwargs.pop('request', None) @@ -80,7 +78,11 @@ class InvalidSchema(RequestException, ValueError): class InvalidURL(RequestException, ValueError): - """ The URL provided was somehow invalid. """ + """The URL provided was somehow invalid.""" + + +class InvalidHeader(RequestException, ValueError): + """The header value provided was somehow invalid.""" class ChunkedEncodingError(RequestException): @@ -108,7 +110,5 @@ class RequestsWarning(Warning): class FileModeWarning(RequestsWarning, DeprecationWarning): - """ - A file was opened in text mode, but Requests determined its binary length. - """ + """A file was opened in text mode, but Requests determined its binary length.""" pass diff --git a/pip/_vendor/requests/hooks.py b/pip/_vendor/requests/hooks.py --- a/pip/_vendor/requests/hooks.py +++ b/pip/_vendor/requests/hooks.py @@ -10,10 +10,10 @@ ``response``: The response generated from a Request. - """ HOOKS = ['response'] + def default_hooks(): return dict((event, []) for event in HOOKS) diff --git a/pip/_vendor/requests/models.py b/pip/_vendor/requests/models.py --- a/pip/_vendor/requests/models.py +++ b/pip/_vendor/requests/models.py @@ -27,7 +27,8 @@ from .utils import ( guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, - iter_slices, guess_json_utf, super_len, to_native_string) + iter_slices, guess_json_utf, super_len, to_native_string, + check_header_validity) from .compat import ( cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO, is_py2, chardet, builtin_str, basestring) @@ -37,11 +38,11 @@ #: The set of HTTP status codes that indicate an automatically #: processable redirect. REDIRECT_STATI = ( - codes.moved, # 301 - codes.found, # 302 - codes.other, # 303 - codes.temporary_redirect, # 307 - codes.permanent_redirect, # 308 + codes.moved, # 301 + codes.found, # 302 + codes.other, # 303 + codes.temporary_redirect, # 307 + codes.permanent_redirect, # 308 ) DEFAULT_REDIRECT_LIMIT = 30 @@ -107,7 +108,6 @@ def _encode_files(files, data): if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). - """ if (not files): raise ValueError("Files must be provided.") @@ -206,8 +206,8 @@ class Request(RequestHooksMixin): >>> req = requests.Request('GET', 'http://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> - """ + def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): @@ -269,7 +269,6 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): >>> s = requests.Session() >>> s.send(r) <Response [200]> - """ def __init__(self): @@ -403,10 +402,13 @@ def prepare_url(self, url, params): def prepare_headers(self, headers): """Prepares the given HTTP headers.""" + self.headers = CaseInsensitiveDict() if headers: - self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) - else: - self.headers = CaseInsensitiveDict() + for header in headers.items(): + # Raise exception on invalid header value. + check_header_validity(header) + name, value = header + self.headers[to_native_string(name)] = value def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" @@ -420,8 +422,12 @@ def prepare_body(self, data, files, json=None): length = None if not data and json is not None: + # urllib3 requires a bytes-like body. Python 2's json.dumps + # provides this natively, but Python 3 gives a Unicode string. content_type = 'application/json' body = complexjson.dumps(json) + if not isinstance(body, bytes): + body = body.encode('utf-8') is_stream = all([ hasattr(data, '__iter__'), @@ -508,8 +514,8 @@ def prepare_cookies(self, cookies): can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" - header is removed beforehand.""" - + header is removed beforehand. + """ if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: @@ -653,6 +659,12 @@ def iter_content(self, chunk_size=1, decode_unicode=False): read into memory. This is not necessarily the length of each item returned as decoding can take place. + chunk_size must be of type int or None. A value of None will + function differently depending on the value of `stream`. + stream=True will read data as it arrives in whatever size the + chunks are received. If stream=False, data is returned as + a single chunk. + If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ @@ -681,6 +693,8 @@ def generate(): if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() + elif chunk_size is not None and not isinstance(chunk_size, int): + raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size)) # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) @@ -792,7 +806,7 @@ def json(self, **kwargs): :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ - if not self.encoding and len(self.content) > 3: + if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make @@ -833,12 +847,16 @@ def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' + if isinstance(self.reason, bytes): + reason = self.reason.decode('utf-8', 'ignore') + else: + reason = self.reason if 400 <= self.status_code < 500: - http_error_msg = '%s Client Error: %s for url: %s' % (self.status_code, self.reason, self.url) + http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url) elif 500 <= self.status_code < 600: - http_error_msg = '%s Server Error: %s for url: %s' % (self.status_code, self.reason, self.url) + http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url) if http_error_msg: raise HTTPError(http_error_msg, response=self) @@ -850,6 +868,6 @@ def close(self): *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: - return self.raw.close() + self.raw.close() return self.raw.release_conn() diff --git a/pip/_vendor/requests/packages/urllib3/__init__.py b/pip/_vendor/requests/packages/urllib3/__init__.py --- a/pip/_vendor/requests/packages/urllib3/__init__.py +++ b/pip/_vendor/requests/packages/urllib3/__init__.py @@ -32,7 +32,7 @@ def emit(self, record): __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)' __license__ = 'MIT' -__version__ = '1.15.1' +__version__ = '1.16' __all__ = ( 'HTTPConnectionPool', diff --git a/pip/_vendor/requests/packages/urllib3/connectionpool.py b/pip/_vendor/requests/packages/urllib3/connectionpool.py --- a/pip/_vendor/requests/packages/urllib3/connectionpool.py +++ b/pip/_vendor/requests/packages/urllib3/connectionpool.py @@ -90,7 +90,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): # Return False to re-raise any potential exceptions return False - def close(): + def close(self): """ Close all pooled connections and disable the pool. """ @@ -163,6 +163,7 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods): scheme = 'http' ConnectionCls = HTTPConnection + ResponseCls = HTTPResponse def __init__(self, host, port=None, strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False, @@ -383,8 +384,13 @@ def _make_request(self, conn, method, url, timeout=_Default, chunked=False, try: try: # Python 2.7, use buffering of HTTP responses httplib_response = conn.getresponse(buffering=True) - except TypeError: # Python 2.6 and older - httplib_response = conn.getresponse() + except TypeError: # Python 2.6 and older, Python 3 + try: + httplib_response = conn.getresponse() + except Exception as e: + # Remove the TypeError from the exception chain in Python 3; + # otherwise it looks like a programming error was the cause. + six.raise_from(e, None) except (SocketTimeout, BaseSSLError, SocketError) as e: self._raise_timeout(err=e, url=url, timeout_value=read_timeout) raise @@ -545,6 +551,17 @@ def urlopen(self, method, url, body=None, headers=None, retries=None, conn = None + # Track whether `conn` needs to be released before + # returning/raising/recursing. Update this variable if necessary, and + # leave `release_conn` constant throughout the function. That way, if + # the function recurses, the original value of `release_conn` will be + # passed down into the recursive call, and its value will be respected. + # + # See issue #651 [1] for details. + # + # [1] <https://github.com/shazow/urllib3/issues/651> + release_this_conn = release_conn + # Merge the proxy headers. Only do this in HTTP. We have to copy the # headers dict so we can safely change it without those changes being # reflected in anyone else's copy. @@ -584,10 +601,10 @@ def urlopen(self, method, url, body=None, headers=None, retries=None, response_conn = conn if not release_conn else None # Import httplib's response into our own wrapper object - response = HTTPResponse.from_httplib(httplib_response, - pool=self, - connection=response_conn, - **response_kw) + response = self.ResponseCls.from_httplib(httplib_response, + pool=self, + connection=response_conn, + **response_kw) # Everything went great! clean_exit = True @@ -633,9 +650,9 @@ def urlopen(self, method, url, body=None, headers=None, retries=None, # Close the connection, set the variable to None, and make sure # we put the None back in the pool to avoid leaking it. conn = conn and conn.close() - release_conn = True + release_this_conn = True - if release_conn: + if release_this_conn: # Put the connection back to be reused. If the connection is # expired then it will be None, which will get replaced with a # fresh connection during _get_conn. @@ -817,7 +834,7 @@ def _validate_conn(self, conn): warnings.warn(( 'Unverified HTTPS request is being made. ' 'Adding certificate verification is strongly advised. See: ' - 'https://urllib3.readthedocs.org/en/latest/security.html'), + 'https://urllib3.readthedocs.io/en/latest/security.html'), InsecureRequestWarning) diff --git a/pip/_vendor/requests/packages/urllib3/contrib/appengine.py b/pip/_vendor/requests/packages/urllib3/contrib/appengine.py --- a/pip/_vendor/requests/packages/urllib3/contrib/appengine.py +++ b/pip/_vendor/requests/packages/urllib3/contrib/appengine.py @@ -70,7 +70,7 @@ def __init__(self, headers=None, retries=None, validate_certificate=True): warnings.warn( "urllib3 is using URLFetch on Google App Engine sandbox instead " "of sockets. To use sockets directly instead of URLFetch see " - "https://urllib3.readthedocs.org/en/latest/contrib.html.", + "https://urllib3.readthedocs.io/en/latest/contrib.html.", AppEnginePlatformWarning) RequestMethods.__init__(self, headers) diff --git a/pip/_vendor/requests/packages/urllib3/contrib/socks.py b/pip/_vendor/requests/packages/urllib3/contrib/socks.py --- a/pip/_vendor/requests/packages/urllib3/contrib/socks.py +++ b/pip/_vendor/requests/packages/urllib3/contrib/socks.py @@ -26,7 +26,7 @@ warnings.warn(( 'SOCKS support in urllib3 requires the installation of optional ' 'dependencies: specifically, PySocks. For more information, see ' - 'https://urllib3.readthedocs.org/en/latest/contrib.html#socks-proxies' + 'https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies' ), DependencyWarning ) diff --git a/pip/_vendor/requests/packages/urllib3/packages/six.py b/pip/_vendor/requests/packages/urllib3/packages/six.py --- a/pip/_vendor/requests/packages/urllib3/packages/six.py +++ b/pip/_vendor/requests/packages/urllib3/packages/six.py @@ -1,34 +1,41 @@ """Utilities for writing code that runs on Python 2 and 3""" -#Copyright (c) 2010-2011 Benjamin Peterson - -#Permission is hereby granted, free of charge, to any person obtaining a copy of -#this software and associated documentation files (the "Software"), to deal in -#the Software without restriction, including without limitation the rights to -#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -#the Software, and to permit persons to whom the Software is furnished to do so, -#subject to the following conditions: - -#The above copyright notice and this permission notice shall be included in all -#copies or substantial portions of the Software. - -#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - +# Copyright (c) 2010-2015 Benjamin Peterson +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from __future__ import absolute_import + +import functools +import itertools import operator import sys import types __author__ = "Benjamin Peterson <benjamin@python.org>" -__version__ = "1.2.0" # Revision 41c74fef2ded +__version__ = "1.10.0" -# True if we are running on Python 3. +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 +PY34 = sys.version_info[0:2] >= (3, 4) if PY3: string_types = str, @@ -51,6 +58,7 @@ else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): + def __len__(self): return 1 << 31 try: @@ -61,7 +69,7 @@ def __len__(self): else: # 64-bit MAXSIZE = int((1 << 63) - 1) - del X + del X def _add_doc(func, doc): @@ -82,9 +90,13 @@ def __init__(self, name): def __get__(self, obj, tp): result = self._resolve() - setattr(obj, self.name, result) - # This is a bit ugly, but it avoids running this again. - delattr(tp, self.name) + setattr(obj, self.name, result) # Invokes __set__. + try: + # This is a bit ugly, but it avoids running this again by + # removing this descriptor. + delattr(obj.__class__, self.name) + except AttributeError: + pass return result @@ -102,6 +114,27 @@ def __init__(self, name, old, new=None): def _resolve(self): return _import_module(self.mod) + def __getattr__(self, attr): + _module = self._resolve() + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + class MovedAttribute(_LazyDescr): @@ -128,30 +161,111 @@ def _resolve(self): return getattr(module, self.attr) +class _SixMetaPathImporter(object): + + """ + A meta path importer to import six.moves and its submodules. + + This class implements a PEP302 finder and loader. It should be compatible + with Python 2.5 and all existing versions of Python3 + """ + + def __init__(self, six_module_name): + self.name = six_module_name + self.known_modules = {} + + def _add_module(self, mod, *fullnames): + for fullname in fullnames: + self.known_modules[self.name + "." + fullname] = mod + + def _get_module(self, fullname): + return self.known_modules[self.name + "." + fullname] + + def find_module(self, fullname, path=None): + if fullname in self.known_modules: + return self + return None + + def __get_module(self, fullname): + try: + return self.known_modules[fullname] + except KeyError: + raise ImportError("This loader does not know module " + fullname) + + def load_module(self, fullname): + try: + # in case of a reload + return sys.modules[fullname] + except KeyError: + pass + mod = self.__get_module(fullname) + if isinstance(mod, MovedModule): + mod = mod._resolve() + else: + mod.__loader__ = self + sys.modules[fullname] = mod + return mod + + def is_package(self, fullname): + """ + Return true, if the named module is a package. + + We need this method to get correct spec objects with + Python 3.4 (see PEP451) + """ + return hasattr(self.__get_module(fullname), "__path__") + + def get_code(self, fullname): + """Return None + + Required, if is_package is implemented""" + self.__get_module(fullname) # eventually raises ImportError + return None + get_source = get_code # same as get_code + +_importer = _SixMetaPathImporter(__name__) + + +class _MovedItems(_LazyModule): -class _MovedItems(types.ModuleType): """Lazy loading of moved objects""" + __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), - MovedAttribute("reload_module", "__builtin__", "imp", "reload"), + MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), + MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserDict", "UserDict", "collections"), + MovedAttribute("UserList", "UserList", "collections"), + MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), - + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), @@ -159,12 +273,14 @@ class _MovedItems(types.ModuleType): MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", @@ -176,14 +292,195 @@ class _MovedItems(types.ModuleType): MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), - MovedModule("winreg", "_winreg"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] +# Add windows specific modules. +if sys.platform == "win32": + _moved_attributes += [ + MovedModule("winreg", "_winreg"), + ] + for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + _importer._add_module(attr, "moves." + attr.name) del attr -moves = sys.modules[__name__ + ".moves"] = _MovedItems("moves") +_MovedItems._moved_attributes = _moved_attributes + +moves = _MovedItems(__name__ + ".moves") +_importer._add_module(moves, "moves") + + +class Module_six_moves_urllib_parse(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), + MovedAttribute("splittag", "urllib", "urllib.parse"), + MovedAttribute("splituser", "urllib", "urllib.parse"), + MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), + MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), + MovedAttribute("uses_params", "urlparse", "urllib.parse"), + MovedAttribute("uses_query", "urlparse", "urllib.parse"), + MovedAttribute("uses_relative", "urlparse", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), + "moves.urllib_parse", "moves.urllib.parse") + + +class Module_six_moves_urllib_error(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), + "moves.urllib_error", "moves.urllib.error") + + +class Module_six_moves_urllib_request(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), +] +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes + +_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), + "moves.urllib_request", "moves.urllib.request") + + +class Module_six_moves_urllib_response(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), + "moves.urllib_response", "moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), + "moves.urllib_robotparser", "moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + __path__ = [] # mark as package + parse = _importer._get_module("moves.urllib_parse") + error = _importer._get_module("moves.urllib_error") + request = _importer._get_module("moves.urllib_request") + response = _importer._get_module("moves.urllib_response") + robotparser = _importer._get_module("moves.urllib_robotparser") + + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] + +_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), + "moves.urllib") def add_move(move): @@ -206,22 +503,18 @@ def remove_move(name): _meth_func = "__func__" _meth_self = "__self__" + _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" - - _iterkeys = "keys" - _itervalues = "values" - _iteritems = "items" + _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" + _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" - - _iterkeys = "iterkeys" - _itervalues = "itervalues" - _iteritems = "iteritems" + _func_globals = "func_globals" try: @@ -232,18 +525,33 @@ def advance_iterator(it): next = advance_iterator +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + if PY3: def get_unbound_function(unbound): return unbound - Iterator = object + create_bound_method = types.MethodType - def callable(obj): - return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + def create_unbound_method(func, cls): + return func + + Iterator = object else: def get_unbound_function(unbound): return unbound.im_func + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + def create_unbound_method(func, cls): + return types.MethodType(func, None, cls) + class Iterator(object): def next(self): @@ -256,90 +564,179 @@ def next(self): get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) + + viewkeys = operator.methodcaller("keys") + + viewvalues = operator.methodcaller("values") + + viewitems = operator.methodcaller("items") +else: + def iterkeys(d, **kw): + return d.iterkeys(**kw) + def itervalues(d, **kw): + return d.itervalues(**kw) -def iterkeys(d): - """Return an iterator over the keys of a dictionary.""" - return iter(getattr(d, _iterkeys)()) + def iteritems(d, **kw): + return d.iteritems(**kw) -def itervalues(d): - """Return an iterator over the values of a dictionary.""" - return iter(getattr(d, _itervalues)()) + def iterlists(d, **kw): + return d.iterlists(**kw) -def iteritems(d): - """Return an iterator over the (key, value) pairs of a dictionary.""" - return iter(getattr(d, _iteritems)()) + viewkeys = operator.methodcaller("viewkeys") + + viewvalues = operator.methodcaller("viewvalues") + + viewitems = operator.methodcaller("viewitems") + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") + def u(s): return s - if sys.version_info[1] <= 1: - def int2byte(i): - return bytes((i,)) - else: - # This is about 2x faster than the implementation above on 3.2+ - int2byte = operator.methodcaller("to_bytes", 1, "big") + unichr = chr + import struct + int2byte = struct.Struct(">B").pack + del struct + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO + _assertCountEqual = "assertCountEqual" + if sys.version_info[1] <= 1: + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" + else: + _assertRaisesRegex = "assertRaisesRegex" + _assertRegex = "assertRegex" else: def b(s): return s + # Workaround for standalone backslash + def u(s): - return unicode(s, "unicode_escape") + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") + unichr = unichr int2byte = chr + + def byte2int(bs): + return ord(bs[0]) + + def indexbytes(buf, i): + return ord(buf[i]) + iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO + _assertCountEqual = "assertItemsEqual" + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") -if PY3: - import builtins - exec_ = getattr(builtins, "exec") +def assertCountEqual(self, *args, **kwargs): + return getattr(self, _assertCountEqual)(*args, **kwargs) + +def assertRaisesRegex(self, *args, **kwargs): + return getattr(self, _assertRaisesRegex)(*args, **kwargs) + + +def assertRegex(self, *args, **kwargs): + return getattr(self, _assertRegex)(*args, **kwargs) + + +if PY3: + exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): + if value is None: + value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value - - print_ = getattr(builtins, "print") - del builtins - else: - def exec_(code, globs=None, locs=None): + def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" - if globs is None: + if _globs_ is None: frame = sys._getframe(1) - globs = frame.f_globals - if locs is None: - locs = frame.f_locals + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals del frame - elif locs is None: - locs = globs - exec("""exec code in globs, locs""") - + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """) +if sys.version_info[:2] == (3, 2): + exec_("""def raise_from(value, from_value): + if from_value is None: + raise value + raise value from from_value +""") +elif sys.version_info[:2] > (3, 2): + exec_("""def raise_from(value, from_value): + raise value from from_value +""") +else: + def raise_from(value, from_value): + raise value + + +print_ = getattr(moves.builtins, "print", None) +if print_ is None: def print_(*args, **kwargs): - """The new-style print function.""" + """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return + def write(data): if not isinstance(data, basestring): data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) @@ -376,10 +773,96 @@ def write(data): write(sep) write(arg) write(end) +if sys.version_info[:2] < (3, 3): + _print = print_ + + def print_(*args, **kwargs): + fp = kwargs.get("file", sys.stdout) + flush = kwargs.pop("flush", False) + _print(*args, **kwargs) + if flush and fp is not None: + fp.flush() _add_doc(reraise, """Reraise an exception.""") +if sys.version_info[0:2] < (3, 4): + def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + def wrapper(f): + f = functools.wraps(wrapped, assigned, updated)(f) + f.__wrapped__ = wrapped + return f + return wrapper +else: + wraps = functools.wraps + -def with_metaclass(meta, base=object): +def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" - return meta("NewBase", (base,), {}) + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(meta): + + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + return type.__new__(metaclass, 'temporary_class', (), {}) + + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper + + +def python_2_unicode_compatible(klass): + """ + A decorator that defines __unicode__ and __str__ methods under Python 2. + Under Python 3 it does nothing. + + To support Python 2 and 3 with a single code base, define a __str__ method + returning text and apply this decorator to the class. + """ + if PY2: + if '__str__' not in klass.__dict__: + raise ValueError("@python_2_unicode_compatible cannot be applied " + "to %s because it doesn't define __str__()." % + klass.__name__) + klass.__unicode__ = klass.__str__ + klass.__str__ = lambda self: self.__unicode__().encode('utf-8') + return klass + + +# Complete the moves implementation. +# This code is at the end of this module to speed up module loading. +# Turn this module into a package. +__path__ = [] # required for PEP 302 and PEP 451 +__package__ = __name__ # see PEP 366 @ReservedAssignment +if globals().get("__spec__") is not None: + __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable +# Remove other six meta path importers, since they cause problems. This can +# happen if six is removed from sys.modules and then reloaded. (Setuptools does +# this for some reason.) +if sys.meta_path: + for i, importer in enumerate(sys.meta_path): + # Here's some real nastiness: Another "instance" of the six module might + # be floating around. Therefore, we can't use isinstance() to check for + # the six meta path importer, since the other six instance will have + # inserted an importer with different class. + if (type(importer).__name__ == "_SixMetaPathImporter" and + importer.name == __name__): + del sys.meta_path[i] + break + del i, importer +# Finally, add the importer to the meta path import hook. +sys.meta_path.append(_importer) diff --git a/pip/_vendor/requests/packages/urllib3/poolmanager.py b/pip/_vendor/requests/packages/urllib3/poolmanager.py --- a/pip/_vendor/requests/packages/urllib3/poolmanager.py +++ b/pip/_vendor/requests/packages/urllib3/poolmanager.py @@ -1,4 +1,6 @@ from __future__ import absolute_import +import collections +import functools import logging try: # Python 3 @@ -23,6 +25,59 @@ SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs', 'ssl_version', 'ca_cert_dir') +# The base fields to use when determining what pool to get a connection from; +# these do not rely on the ``connection_pool_kw`` and can be determined by the +# URL and potentially the ``urllib3.connection.port_by_scheme`` dictionary. +# +# All custom key schemes should include the fields in this key at a minimum. +BasePoolKey = collections.namedtuple('BasePoolKey', ('scheme', 'host', 'port')) + +# The fields to use when determining what pool to get a HTTP and HTTPS +# connection from. All additional fields must be present in the PoolManager's +# ``connection_pool_kw`` instance variable. +HTTPPoolKey = collections.namedtuple( + 'HTTPPoolKey', BasePoolKey._fields + ('timeout', 'retries', 'strict', + 'block', 'source_address') +) +HTTPSPoolKey = collections.namedtuple( + 'HTTPSPoolKey', HTTPPoolKey._fields + SSL_KEYWORDS +) + + +def _default_key_normalizer(key_class, request_context): + """ + Create a pool key of type ``key_class`` for a request. + + According to RFC 3986, both the scheme and host are case-insensitive. + Therefore, this function normalizes both before constructing the pool + key for an HTTPS request. If you wish to change this behaviour, provide + alternate callables to ``key_fn_by_scheme``. + + :param key_class: + The class to use when constructing the key. This should be a namedtuple + with the ``scheme`` and ``host`` keys at a minimum. + + :param request_context: + A dictionary-like object that contain the context for a request. + It should contain a key for each field in the :class:`HTTPPoolKey` + """ + context = {} + for key in key_class._fields: + context[key] = request_context.get(key) + context['scheme'] = context['scheme'].lower() + context['host'] = context['host'].lower() + return key_class(**context) + + +# A dictionary that maps a scheme to a callable that creates a pool key. +# This can be used to alter the way pool keys are constructed, if desired. +# Each PoolManager makes a copy of this dictionary so they can be configured +# globally here, or individually on the instance. +key_fn_by_scheme = { + 'http': functools.partial(_default_key_normalizer, HTTPPoolKey), + 'https': functools.partial(_default_key_normalizer, HTTPSPoolKey), +} + pool_classes_by_scheme = { 'http': HTTPConnectionPool, 'https': HTTPSConnectionPool, @@ -65,8 +120,10 @@ def __init__(self, num_pools=10, headers=None, **connection_pool_kw): self.pools = RecentlyUsedContainer(num_pools, dispose_func=lambda p: p.close()) - # Locally set the pool classes so other PoolManagers can override them. + # Locally set the pool classes and keys so other PoolManagers can + # override them. self.pool_classes_by_scheme = pool_classes_by_scheme + self.key_fn_by_scheme = key_fn_by_scheme.copy() def __enter__(self): return self @@ -113,10 +170,36 @@ def connection_from_host(self, host, port=None, scheme='http'): if not host: raise LocationValueError("No host specified.") - scheme = scheme or 'http' - port = port or port_by_scheme.get(scheme, 80) - pool_key = (scheme, host, port) + request_context = self.connection_pool_kw.copy() + request_context['scheme'] = scheme or 'http' + if not port: + port = port_by_scheme.get(request_context['scheme'].lower(), 80) + request_context['port'] = port + request_context['host'] = host + + return self.connection_from_context(request_context) + def connection_from_context(self, request_context): + """ + Get a :class:`ConnectionPool` based on the request context. + + ``request_context`` must at least contain the ``scheme`` key and its + value must be a key in ``key_fn_by_scheme`` instance variable. + """ + scheme = request_context['scheme'].lower() + pool_key_constructor = self.key_fn_by_scheme[scheme] + pool_key = pool_key_constructor(request_context) + + return self.connection_from_pool_key(pool_key) + + def connection_from_pool_key(self, pool_key): + """ + Get a :class:`ConnectionPool` based on the provided pool key. + + ``pool_key`` should be a namedtuple that only contains immutable + objects. At a minimum it must have the ``scheme``, ``host``, and + ``port`` fields. + """ with self.pools.lock: # If the scheme, host, or port doesn't match existing open # connections, open a new ConnectionPool. @@ -125,7 +208,7 @@ def connection_from_host(self, host, port=None, scheme='http'): return pool # Make a fresh ConnectionPool of the desired type - pool = self._new_pool(scheme, host, port) + pool = self._new_pool(pool_key.scheme, pool_key.host, pool_key.port) self.pools[pool_key] = pool return pool diff --git a/pip/_vendor/requests/packages/urllib3/response.py b/pip/_vendor/requests/packages/urllib3/response.py --- a/pip/_vendor/requests/packages/urllib3/response.py +++ b/pip/_vendor/requests/packages/urllib3/response.py @@ -165,6 +165,10 @@ def data(self): if self._fp: return self.read(cache_content=True) + @property + def connection(self): + return self._connection + def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from diff --git a/pip/_vendor/requests/packages/urllib3/util/connection.py b/pip/_vendor/requests/packages/urllib3/util/connection.py --- a/pip/_vendor/requests/packages/urllib3/util/connection.py +++ b/pip/_vendor/requests/packages/urllib3/util/connection.py @@ -46,6 +46,8 @@ def is_connection_dropped(conn): # Platform-specific # This function is copied from socket.py in the Python 2.7 standard # library test suite. Added to its signature is only `socket_options`. +# One additional modification is that we avoid binding to IPv6 servers +# discovered in DNS if the system doesn't have IPv6 functionality. def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): """Connect to *address* and return the socket object. @@ -64,14 +66,19 @@ def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, if host.startswith('['): host = host.strip('[]') err = None - for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): + + # Using the value from allowed_gai_family() in the context of getaddrinfo lets + # us select whether to work with IPv4 DNS records, IPv6 records, or both. + # The original create_connection function always returns all records. + family = allowed_gai_family() + + for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. - # This is the only addition urllib3 makes to this function. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: @@ -99,3 +106,39 @@ def _set_socket_options(sock, options): for opt in options: sock.setsockopt(*opt) + + +def allowed_gai_family(): + """This function is designed to work in the context of + getaddrinfo, where family=socket.AF_UNSPEC is the default and + will perform a DNS search for both IPv6 and IPv4 records.""" + + family = socket.AF_INET + if HAS_IPV6: + family = socket.AF_UNSPEC + return family + + +def _has_ipv6(host): + """ Returns True if the system can bind an IPv6 address. """ + sock = None + has_ipv6 = False + + if socket.has_ipv6: + # has_ipv6 returns true if cPython was compiled with IPv6 support. + # It does not tell us if the system has IPv6 support enabled. To + # determine that we must bind to an IPv6 address. + # https://github.com/shazow/urllib3/pull/611 + # https://bugs.python.org/issue658327 + try: + sock = socket.socket(socket.AF_INET6) + sock.bind((host, 0)) + has_ipv6 = True + except Exception: + pass + + if sock: + sock.close() + return has_ipv6 + +HAS_IPV6 = _has_ipv6('::1') diff --git a/pip/_vendor/requests/packages/urllib3/util/retry.py b/pip/_vendor/requests/packages/urllib3/util/retry.py --- a/pip/_vendor/requests/packages/urllib3/util/retry.py +++ b/pip/_vendor/requests/packages/urllib3/util/retry.py @@ -80,21 +80,27 @@ class Retry(object): Set of uppercased HTTP method verbs that we should retry on. By default, we only retry on methods which are considered to be - indempotent (multiple requests with the same parameters end with the + idempotent (multiple requests with the same parameters end with the same state). See :attr:`Retry.DEFAULT_METHOD_WHITELIST`. + Set to a ``False`` value to retry on any verb. + :param iterable status_forcelist: - A set of HTTP status codes that we should force a retry on. + A set of integer HTTP status codes that we should force a retry on. + A retry is initiated if the request method is in ``method_whitelist`` + and the response status code is in ``status_forcelist``. By default, this is disabled with ``None``. :param float backoff_factor: - A backoff factor to apply between attempts. urllib3 will sleep for:: + A backoff factor to apply between attempts after the second try + (most errors are resolved immediately by a second try without a + delay). urllib3 will sleep for:: {backoff factor} * (2 ^ ({number of total retries} - 1)) seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep - for [0.1s, 0.2s, 0.4s, ...] between retries. It will never be longer + for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer than :attr:`Retry.BACKOFF_MAX`. By default, backoff is disabled (set to 0). diff --git a/pip/_vendor/requests/packages/urllib3/util/ssl_.py b/pip/_vendor/requests/packages/urllib3/util/ssl_.py --- a/pip/_vendor/requests/packages/urllib3/util/ssl_.py +++ b/pip/_vendor/requests/packages/urllib3/util/ssl_.py @@ -117,7 +117,7 @@ def wrap_socket(self, socket, server_hostname=None, server_side=False): 'urllib3 from configuring SSL appropriately and may cause ' 'certain SSL connections to fail. You can upgrade to a newer ' 'version of Python to solve this. For more information, see ' - 'https://urllib3.readthedocs.org/en/latest/security.html' + 'https://urllib3.readthedocs.io/en/latest/security.html' '#insecureplatformwarning.', InsecurePlatformWarning ) @@ -313,7 +313,7 @@ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, 'This may cause the server to present an incorrect TLS ' 'certificate, which can cause validation failures. You can upgrade to ' 'a newer version of Python to solve this. For more information, see ' - 'https://urllib3.readthedocs.org/en/latest/security.html' + 'https://urllib3.readthedocs.io/en/latest/security.html' '#snimissingwarning.', SNIMissingWarning ) diff --git a/pip/_vendor/requests/sessions.py b/pip/_vendor/requests/sessions.py --- a/pip/_vendor/requests/sessions.py +++ b/pip/_vendor/requests/sessions.py @@ -6,7 +6,6 @@ This module provides a Session object to manage and persist settings across requests (cookies, auth, proxies). - """ import os from collections import Mapping @@ -40,9 +39,8 @@ def merge_setting(request_setting, session_setting, dict_class=OrderedDict): - """ - Determines appropriate setting for a given request, taking into account the - explicit setting on that request, and the setting in the session. If a + """Determines appropriate setting for a given request, taking into account + the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ @@ -72,8 +70,7 @@ def merge_setting(request_setting, session_setting, dict_class=OrderedDict): def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): - """ - Properly merges both requests and session hooks. + """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. @@ -143,9 +140,10 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None, # https://github.com/kennethreitz/requests/issues/1084 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect): - if 'Content-Length' in prepared_request.headers: - del prepared_request.headers['Content-Length'] - + # https://github.com/kennethreitz/requests/issues/3490 + purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding') + for header in purged_headers: + prepared_request.headers.pop(header, None) prepared_request.body = None headers = prepared_request.headers @@ -185,8 +183,7 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None, yield resp def rebuild_auth(self, prepared_request, response): - """ - When being redirected we may want to strip authentication from the + """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ @@ -195,7 +192,7 @@ def rebuild_auth(self, prepared_request, response): if 'Authorization' in headers: # If we get redirected to a new host, we should strip out any - # authentication headers. + # authentication headers. original_parsed = urlparse(response.request.url) redirect_parsed = urlparse(url) @@ -210,8 +207,7 @@ def rebuild_auth(self, prepared_request, response): return def rebuild_proxies(self, prepared_request, proxies): - """ - This method re-evaluates the proxy configuration by considering the + """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous @@ -219,6 +215,8 @@ def rebuild_proxies(self, prepared_request, proxies): This method also replaces the Proxy-Authorization header where necessary. + + :rtype: dict """ headers = prepared_request.headers url = prepared_request.url @@ -228,10 +226,10 @@ def rebuild_proxies(self, prepared_request, proxies): if self.trust_env and not should_bypass_proxies(url): environ_proxies = get_environ_proxies(url) - proxy = environ_proxies.get(scheme) + proxy = environ_proxies.get('all', environ_proxies.get(scheme)) if proxy: - new_proxies.setdefault(scheme, environ_proxies[scheme]) + new_proxies.setdefault(scheme, proxy) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] @@ -329,6 +327,8 @@ def __init__(self): #: Maximum number of redirects allowed. If the request exceeds this #: limit, a :class:`TooManyRedirects` exception is raised. + #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is + #: 30. self.max_redirects = DEFAULT_REDIRECT_LIMIT #: Trust environment settings for proxy configuration, default @@ -363,6 +363,7 @@ def prepare_request(self, request): :param request: :class:`Request` instance to prepare with this session's settings. + :rtype: requests.PreparedRequest """ cookies = request.cookies or {} @@ -374,7 +375,6 @@ def prepare_request(self, request): merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) - # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: @@ -444,7 +444,7 @@ def request(self, method, url, :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response - """ + """ # Create the Request. req = Request( method = method.upper(), @@ -481,6 +481,7 @@ def get(self, url, **kwargs): :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) @@ -491,6 +492,7 @@ def options(self, url, **kwargs): :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) @@ -501,6 +503,7 @@ def head(self, url, **kwargs): :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) @@ -513,6 +516,7 @@ def post(self, url, data=None, json=None, **kwargs): :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response """ return self.request('POST', url, data=data, json=json, **kwargs) @@ -523,6 +527,7 @@ def put(self, url, data=None, **kwargs): :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response """ return self.request('PUT', url, data=data, **kwargs) @@ -533,6 +538,7 @@ def patch(self, url, data=None, **kwargs): :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response """ return self.request('PATCH', url, data=data, **kwargs) @@ -542,12 +548,17 @@ def delete(self, url, **kwargs): :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. + :rtype: requests.Response """ return self.request('DELETE', url, **kwargs) def send(self, request, **kwargs): - """Send a given PreparedRequest.""" + """ + Send a given PreparedRequest. + + :rtype: requests.Response + """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) @@ -619,7 +630,11 @@ def send(self, request, **kwargs): return r def merge_environment_settings(self, url, proxies, stream, verify, cert): - """Check the environment and merge it with some settings.""" + """ + Check the environment and merge it with some settings. + + :rtype: dict + """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. @@ -643,7 +658,11 @@ def merge_environment_settings(self, url, proxies, stream, verify, cert): 'cert': cert} def get_adapter(self, url): - """Returns the appropriate connection adapter for the given URL.""" + """ + Returns the appropriate connection adapter for the given URL. + + :rtype: requests.adapters.BaseAdapter + """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix): @@ -660,8 +679,8 @@ def close(self): def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. - Adapters are sorted in descending order by key length.""" - + Adapters are sorted in descending order by key length. + """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] @@ -684,6 +703,10 @@ def __setstate__(self, state): def session(): - """Returns a :class:`Session` for context-management.""" + """ + Returns a :class:`Session` for context-management. + + :rtype: Session + """ return Session() diff --git a/pip/_vendor/requests/status_codes.py b/pip/_vendor/requests/status_codes.py --- a/pip/_vendor/requests/status_codes.py +++ b/pip/_vendor/requests/status_codes.py @@ -31,7 +31,7 @@ 306: ('switch_proxy',), 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 308: ('permanent_redirect', - 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 + 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 # Client Error. 400: ('bad_request', 'bad'), diff --git a/pip/_vendor/requests/structures.py b/pip/_vendor/requests/structures.py --- a/pip/_vendor/requests/structures.py +++ b/pip/_vendor/requests/structures.py @@ -5,7 +5,6 @@ ~~~~~~~~~~~~~~~~~~~ Data structures that power Requests. - """ import collections @@ -14,8 +13,7 @@ class CaseInsensitiveDict(collections.MutableMapping): - """ - A case-insensitive ``dict``-like object. + """A case-insensitive ``dict``-like object. Implements all methods and operations of ``collections.MutableMapping`` as well as dict's ``copy``. Also @@ -39,8 +37,8 @@ class CaseInsensitiveDict(collections.MutableMapping): If the constructor, ``.update``, or equality comparison operations are given keys that have equal ``.lower()``s, the behavior is undefined. - """ + def __init__(self, data=None, **kwargs): self._store = OrderedDict() if data is None: @@ -87,6 +85,7 @@ def copy(self): def __repr__(self): return str(dict(self.items())) + class LookupDict(dict): """Dictionary lookup object.""" diff --git a/pip/_vendor/requests/utils.py b/pip/_vendor/requests/utils.py --- a/pip/_vendor/requests/utils.py +++ b/pip/_vendor/requests/utils.py @@ -6,7 +6,6 @@ This module provides utility functions that are used within Requests that are also useful for external consumption. - """ import cgi @@ -27,7 +26,7 @@ basestring) from .cookies import RequestsCookieJar, cookiejar_from_dict from .structures import CaseInsensitiveDict -from .exceptions import InvalidURL, FileModeWarning +from .exceptions import InvalidURL, InvalidHeader, FileModeWarning _hush_pyflakes = (RequestsCookieJar,) @@ -165,6 +164,8 @@ def from_key_val_list(value): ValueError: need more than 1 value to unpack >>> from_key_val_list({'key': 'val'}) OrderedDict([('key', 'val')]) + + :rtype: OrderedDict """ if value is None: return None @@ -187,6 +188,8 @@ def to_key_val_list(value): [('key', 'val')] >>> to_key_val_list('string') ValueError: cannot encode objects that are not 2-tuples. + + :rtype: list """ if value is None: return None @@ -222,6 +225,7 @@ def parse_list_header(value): :param value: a string with a list header. :return: :class:`list` + :rtype: list """ result = [] for item in _parse_list_header(value): @@ -252,6 +256,7 @@ def parse_dict_header(value): :param value: a string with a dict header. :return: :class:`dict` + :rtype: dict """ result = {} for item in _parse_list_header(value): @@ -272,6 +277,7 @@ def unquote_header_value(value, is_filename=False): using for quoting. :param value: the header value to unquote. + :rtype: str """ if value and value[0] == value[-1] == '"': # this is not the real unquoting, but fixing this so that the @@ -294,6 +300,7 @@ def dict_from_cookiejar(cj): """Returns a key/value dictionary from a CookieJar. :param cj: CookieJar object to extract cookies from. + :rtype: dict """ cookie_dict = {} @@ -309,6 +316,7 @@ def add_dict_to_cookiejar(cj, cookie_dict): :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. + :rtype: CookieJar """ cj2 = cookiejar_from_dict(cookie_dict) @@ -340,6 +348,7 @@ def get_encoding_from_headers(headers): """Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from. + :rtype: str """ content_type = headers.get('content-type') @@ -377,6 +386,8 @@ def stream_decode_response_unicode(iterator, r): def iter_slices(string, slice_length): """Iterate over slices of a string.""" pos = 0 + if slice_length is None or slice_length <= 0: + slice_length = len(string) while pos < len(string): yield string[pos:pos + slice_length] pos += slice_length @@ -392,6 +403,7 @@ def get_unicode_from_response(r): 1. charset from content-type 2. fall back and replace all unicode characters + :rtype: str """ warnings.warn(( 'In requests 3.0, get_unicode_from_response will be removed. For ' @@ -426,6 +438,8 @@ def get_unicode_from_response(r): def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. + + :rtype: str """ parts = uri.split('%') for i in range(1, len(parts)): @@ -450,6 +464,8 @@ def requote_uri(uri): This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. + + :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" @@ -466,10 +482,12 @@ def requote_uri(uri): def address_in_network(ip, net): - """ - This function allows you to check if on IP belongs to a network subnet + """This function allows you to check if on IP belongs to a network subnet + Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 + + :rtype: bool """ ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0] netaddr, bits = net.split('/') @@ -479,15 +497,20 @@ def address_in_network(ip, net): def dotted_netmask(mask): - """ - Converts mask from /xx format to xxx.xxx.xxx.xxx + """Converts mask from /xx format to xxx.xxx.xxx.xxx + Example: if mask is 24 function returns 255.255.255.0 + + :rtype: str """ bits = 0xffffffff ^ (1 << 32 - mask) - 1 return socket.inet_ntoa(struct.pack('>I', bits)) def is_ipv4_address(string_ip): + """ + :rtype: bool + """ try: socket.inet_aton(string_ip) except socket.error: @@ -496,7 +519,11 @@ def is_ipv4_address(string_ip): def is_valid_cidr(string_network): - """Very simple check of the cidr format in no_proxy variable""" + """ + Very simple check of the cidr format in no_proxy variable. + + :rtype: bool + """ if string_network.count('/') == 1: try: mask = int(string_network.split('/')[1]) @@ -518,6 +545,8 @@ def is_valid_cidr(string_network): def should_bypass_proxies(url): """ Returns whether we should bypass proxies or not. + + :rtype: bool """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) @@ -539,6 +568,10 @@ def should_bypass_proxies(url): if is_valid_cidr(proxy_ip): if address_in_network(ip, proxy_ip): return True + elif ip == proxy_ip: + # If no_proxy ip was defined in plain IP notation instead of cidr notation & + # matches the IP of the index + return True else: for host in no_proxy: if netloc.endswith(host) or netloc.split(':')[0].endswith(host): @@ -564,7 +597,11 @@ def should_bypass_proxies(url): def get_environ_proxies(url): - """Return a dict of environment proxies.""" + """ + Return a dict of environment proxies. + + :rtype: dict + """ if should_bypass_proxies(url): return {} else: @@ -580,20 +617,36 @@ def select_proxy(url, proxies): proxies = proxies or {} urlparts = urlparse(url) if urlparts.hostname is None: - proxy = None - else: - proxy = proxies.get(urlparts.scheme+'://'+urlparts.hostname) - if proxy is None: - proxy = proxies.get(urlparts.scheme) + return proxies.get('all', proxies.get(urlparts.scheme)) + + proxy_keys = [ + 'all://' + urlparts.hostname, + 'all', + urlparts.scheme + '://' + urlparts.hostname, + urlparts.scheme, + ] + proxy = None + for proxy_key in proxy_keys: + if proxy_key in proxies: + proxy = proxies[proxy_key] + break + return proxy def default_user_agent(name="python-requests"): - """Return a string representing the default user agent.""" + """ + Return a string representing the default user agent. + + :rtype: str + """ return '%s/%s' % (name, __version__) def default_headers(): + """ + :rtype: requests.structures.CaseInsensitiveDict + """ return CaseInsensitiveDict({ 'User-Agent': default_user_agent(), 'Accept-Encoding': ', '.join(('gzip', 'deflate')), @@ -607,6 +660,7 @@ def parse_header_links(value): i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg" + :rtype: list """ links = [] @@ -641,6 +695,9 @@ def parse_header_links(value): def guess_json_utf(data): + """ + :rtype: str + """ # JSON always starts with two ASCII characters, so detection is as # easy as counting the nulls and from their location and count # determine the encoding. Also detect a BOM, if present. @@ -671,7 +728,10 @@ def guess_json_utf(data): def prepend_scheme_if_needed(url, new_scheme): """Given a URL that may or may not have a scheme, prepend the given scheme. - Does not replace a present scheme with the one provided as an argument.""" + Does not replace a present scheme with the one provided as an argument. + + :rtype: str + """ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme) # urlparse is a finicky beast, and sometimes decides that there isn't a @@ -685,7 +745,10 @@ def prepend_scheme_if_needed(url, new_scheme): def get_auth_from_url(url): """Given a url with authentication components, extract them into a tuple of - username,password.""" + username,password. + + :rtype: (str,str) + """ parsed = urlparse(url) try: @@ -697,10 +760,9 @@ def get_auth_from_url(url): def to_native_string(string, encoding='ascii'): - """ - Given a string object, regardless of type, returns a representation of that - string in the native string type, encoding and decoding where necessary. - This assumes ASCII unless told otherwise. + """Given a string object, regardless of type, returns a representation of + that string in the native string type, encoding and decoding where + necessary. This assumes ASCII unless told otherwise. """ if isinstance(string, builtin_str): out = string @@ -713,9 +775,36 @@ def to_native_string(string, encoding='ascii'): return out +# Moved outside of function to avoid recompile every call +_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$') +_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$') + +def check_header_validity(header): + """Verifies that header value is a string which doesn't contain + leading whitespace or return characters. This prevents unintended + header injection. + + :param header: tuple, in the format (name, value). + """ + name, value = header + + if isinstance(value, bytes): + pat = _CLEAN_HEADER_REGEX_BYTE + else: + pat = _CLEAN_HEADER_REGEX_STR + try: + if not pat.match(value): + raise InvalidHeader("Invalid return character or leading space in header: %s" % name) + except TypeError: + raise InvalidHeader("Header value %s must be of type str or bytes, " + "not %s" % (value, type(value))) + + def urldefragauth(url): """ - Given a url remove the fragment and the authentication part + Given a url remove the fragment and the authentication part. + + :rtype: str """ scheme, netloc, path, params, query, fragment = urlparse(url) diff --git a/pip/_vendor/webencodings/__init__.py b/pip/_vendor/webencodings/__init__.py new file mode 100644 --- /dev/null +++ b/pip/_vendor/webencodings/__init__.py @@ -0,0 +1,342 @@ +# coding: utf8 +""" + + webencodings + ~~~~~~~~~~~~ + + This is a Python implementation of the `WHATWG Encoding standard + <http://encoding.spec.whatwg.org/>`. See README for details. + + :copyright: Copyright 2012 by Simon Sapin + :license: BSD, see LICENSE for details. + +""" + +from __future__ import unicode_literals + +import codecs + +from .labels import LABELS + + +VERSION = '0.5' + + +# Some names in Encoding are not valid Python aliases. Remap these. +PYTHON_NAMES = { + 'iso-8859-8-i': 'iso-8859-8', + 'x-mac-cyrillic': 'mac-cyrillic', + 'macintosh': 'mac-roman', + 'windows-874': 'cp874'} + +CACHE = {} + + +def ascii_lower(string): + r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z. + + :param string: An Unicode string. + :returns: A new Unicode string. + + This is used for `ASCII case-insensitive + <http://encoding.spec.whatwg.org/#ascii-case-insensitive>`_ + matching of encoding labels. + The same matching is also used, among other things, + for `CSS keywords <http://dev.w3.org/csswg/css-values/#keywords>`_. + + This is different from the :meth:`~py:str.lower` method of Unicode strings + which also affect non-ASCII characters, + sometimes mapping them into the ASCII range: + + >>> keyword = u'Bac\N{KELVIN SIGN}ground' + >>> assert keyword.lower() == u'background' + >>> assert ascii_lower(keyword) != keyword.lower() + >>> assert ascii_lower(keyword) == u'bac\N{KELVIN SIGN}ground' + + """ + # This turns out to be faster than unicode.translate() + return string.encode('utf8').lower().decode('utf8') + + +def lookup(label): + """ + Look for an encoding by its label. + This is the spec’s `get an encoding + <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm. + Supported labels are listed there. + + :param label: A string. + :returns: + An :class:`Encoding` object, or :obj:`None` for an unknown label. + + """ + # Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020. + label = ascii_lower(label.strip('\t\n\f\r ')) + name = LABELS.get(label) + if name is None: + return None + encoding = CACHE.get(name) + if encoding is None: + if name == 'x-user-defined': + from .x_user_defined import codec_info + else: + python_name = PYTHON_NAMES.get(name, name) + # Any python_name value that gets to here should be valid. + codec_info = codecs.lookup(python_name) + encoding = Encoding(name, codec_info) + CACHE[name] = encoding + return encoding + + +def _get_encoding(encoding_or_label): + """ + Accept either an encoding object or label. + + :param encoding: An :class:`Encoding` object or a label string. + :returns: An :class:`Encoding` object. + :raises: :exc:`~exceptions.LookupError` for an unknown label. + + """ + if hasattr(encoding_or_label, 'codec_info'): + return encoding_or_label + + encoding = lookup(encoding_or_label) + if encoding is None: + raise LookupError('Unknown encoding label: %r' % encoding_or_label) + return encoding + + +class Encoding(object): + """Reresents a character encoding such as UTF-8, + that can be used for decoding or encoding. + + .. attribute:: name + + Canonical name of the encoding + + .. attribute:: codec_info + + The actual implementation of the encoding, + a stdlib :class:`~codecs.CodecInfo` object. + See :func:`codecs.register`. + + """ + def __init__(self, name, codec_info): + self.name = name + self.codec_info = codec_info + + def __repr__(self): + return '<Encoding %s>' % self.name + + +#: The UTF-8 encoding. Should be used for new content and formats. +UTF8 = lookup('utf-8') + +_UTF16LE = lookup('utf-16le') +_UTF16BE = lookup('utf-16be') + + +def decode(input, fallback_encoding, errors='replace'): + """ + Decode a single string. + + :param input: A byte string + :param fallback_encoding: + An :class:`Encoding` object or a label string. + The encoding to use if :obj:`input` does note have a BOM. + :param errors: Type of error handling. See :func:`codecs.register`. + :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. + :return: + A ``(output, encoding)`` tuple of an Unicode string + and an :obj:`Encoding`. + + """ + # Fail early if `encoding` is an invalid label. + fallback_encoding = _get_encoding(fallback_encoding) + bom_encoding, input = _detect_bom(input) + encoding = bom_encoding or fallback_encoding + return encoding.codec_info.decode(input, errors)[0], encoding + + +def _detect_bom(input): + """Return (bom_encoding, input), with any BOM removed from the input.""" + if input.startswith(b'\xFF\xFE'): + return _UTF16LE, input[2:] + if input.startswith(b'\xFE\xFF'): + return _UTF16BE, input[2:] + if input.startswith(b'\xEF\xBB\xBF'): + return UTF8, input[3:] + return None, input + + +def encode(input, encoding=UTF8, errors='strict'): + """ + Encode a single string. + + :param input: An Unicode string. + :param encoding: An :class:`Encoding` object or a label string. + :param errors: Type of error handling. See :func:`codecs.register`. + :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. + :return: A byte string. + + """ + return _get_encoding(encoding).codec_info.encode(input, errors)[0] + + +def iter_decode(input, fallback_encoding, errors='replace'): + """ + "Pull"-based decoder. + + :param input: + An iterable of byte strings. + + The input is first consumed just enough to determine the encoding + based on the precense of a BOM, + then consumed on demand when the return value is. + :param fallback_encoding: + An :class:`Encoding` object or a label string. + The encoding to use if :obj:`input` does note have a BOM. + :param errors: Type of error handling. See :func:`codecs.register`. + :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. + :returns: + An ``(output, encoding)`` tuple. + :obj:`output` is an iterable of Unicode strings, + :obj:`encoding` is the :obj:`Encoding` that is being used. + + """ + + decoder = IncrementalDecoder(fallback_encoding, errors) + generator = _iter_decode_generator(input, decoder) + encoding = next(generator) + return generator, encoding + + +def _iter_decode_generator(input, decoder): + """Return a generator that first yields the :obj:`Encoding`, + then yields output chukns as Unicode strings. + + """ + decode = decoder.decode + input = iter(input) + for chunck in input: + output = decode(chunck) + if output: + assert decoder.encoding is not None + yield decoder.encoding + yield output + break + else: + # Input exhausted without determining the encoding + output = decode(b'', final=True) + assert decoder.encoding is not None + yield decoder.encoding + if output: + yield output + return + + for chunck in input: + output = decode(chunck) + if output: + yield output + output = decode(b'', final=True) + if output: + yield output + + +def iter_encode(input, encoding=UTF8, errors='strict'): + """ + “Pull”-based encoder. + + :param input: An iterable of Unicode strings. + :param encoding: An :class:`Encoding` object or a label string. + :param errors: Type of error handling. See :func:`codecs.register`. + :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. + :returns: An iterable of byte strings. + + """ + # Fail early if `encoding` is an invalid label. + encode = IncrementalEncoder(encoding, errors).encode + return _iter_encode_generator(input, encode) + + +def _iter_encode_generator(input, encode): + for chunck in input: + output = encode(chunck) + if output: + yield output + output = encode('', final=True) + if output: + yield output + + +class IncrementalDecoder(object): + """ + “Push”-based decoder. + + :param fallback_encoding: + An :class:`Encoding` object or a label string. + The encoding to use if :obj:`input` does note have a BOM. + :param errors: Type of error handling. See :func:`codecs.register`. + :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. + + """ + def __init__(self, fallback_encoding, errors='replace'): + # Fail early if `encoding` is an invalid label. + self._fallback_encoding = _get_encoding(fallback_encoding) + self._errors = errors + self._buffer = b'' + self._decoder = None + #: The actual :class:`Encoding` that is being used, + #: or :obj:`None` if that is not determined yet. + #: (Ie. if there is not enough input yet to determine + #: if there is a BOM.) + self.encoding = None # Not known yet. + + def decode(self, input, final=False): + """Decode one chunk of the input. + + :param input: A byte string. + :param final: + Indicate that no more input is available. + Must be :obj:`True` if this is the last call. + :returns: An Unicode string. + + """ + decoder = self._decoder + if decoder is not None: + return decoder(input, final) + + input = self._buffer + input + encoding, input = _detect_bom(input) + if encoding is None: + if len(input) < 3 and not final: # Not enough data yet. + self._buffer = input + return '' + else: # No BOM + encoding = self._fallback_encoding + decoder = encoding.codec_info.incrementaldecoder(self._errors).decode + self._decoder = decoder + self.encoding = encoding + return decoder(input, final) + + +class IncrementalEncoder(object): + """ + “Push”-based encoder. + + :param encoding: An :class:`Encoding` object or a label string. + :param errors: Type of error handling. See :func:`codecs.register`. + :raises: :exc:`~exceptions.LookupError` for an unknown encoding label. + + .. method:: encode(input, final=False) + + :param input: An Unicode string. + :param final: + Indicate that no more input is available. + Must be :obj:`True` if this is the last call. + :returns: A byte string. + + """ + def __init__(self, encoding=UTF8, errors='strict'): + encoding = _get_encoding(encoding) + self.encode = encoding.codec_info.incrementalencoder(errors).encode diff --git a/pip/_vendor/webencodings/labels.py b/pip/_vendor/webencodings/labels.py new file mode 100644 --- /dev/null +++ b/pip/_vendor/webencodings/labels.py @@ -0,0 +1,231 @@ +""" + + webencodings.labels + ~~~~~~~~~~~~~~~~~~~ + + Map encoding labels to their name. + + :copyright: Copyright 2012 by Simon Sapin + :license: BSD, see LICENSE for details. + +""" + +# XXX Do not edit! +# This file is automatically generated by mklabels.py + +LABELS = { + 'unicode-1-1-utf-8': 'utf-8', + 'utf-8': 'utf-8', + 'utf8': 'utf-8', + '866': 'ibm866', + 'cp866': 'ibm866', + 'csibm866': 'ibm866', + 'ibm866': 'ibm866', + 'csisolatin2': 'iso-8859-2', + 'iso-8859-2': 'iso-8859-2', + 'iso-ir-101': 'iso-8859-2', + 'iso8859-2': 'iso-8859-2', + 'iso88592': 'iso-8859-2', + 'iso_8859-2': 'iso-8859-2', + 'iso_8859-2:1987': 'iso-8859-2', + 'l2': 'iso-8859-2', + 'latin2': 'iso-8859-2', + 'csisolatin3': 'iso-8859-3', + 'iso-8859-3': 'iso-8859-3', + 'iso-ir-109': 'iso-8859-3', + 'iso8859-3': 'iso-8859-3', + 'iso88593': 'iso-8859-3', + 'iso_8859-3': 'iso-8859-3', + 'iso_8859-3:1988': 'iso-8859-3', + 'l3': 'iso-8859-3', + 'latin3': 'iso-8859-3', + 'csisolatin4': 'iso-8859-4', + 'iso-8859-4': 'iso-8859-4', + 'iso-ir-110': 'iso-8859-4', + 'iso8859-4': 'iso-8859-4', + 'iso88594': 'iso-8859-4', + 'iso_8859-4': 'iso-8859-4', + 'iso_8859-4:1988': 'iso-8859-4', + 'l4': 'iso-8859-4', + 'latin4': 'iso-8859-4', + 'csisolatincyrillic': 'iso-8859-5', + 'cyrillic': 'iso-8859-5', + 'iso-8859-5': 'iso-8859-5', + 'iso-ir-144': 'iso-8859-5', + 'iso8859-5': 'iso-8859-5', + 'iso88595': 'iso-8859-5', + 'iso_8859-5': 'iso-8859-5', + 'iso_8859-5:1988': 'iso-8859-5', + 'arabic': 'iso-8859-6', + 'asmo-708': 'iso-8859-6', + 'csiso88596e': 'iso-8859-6', + 'csiso88596i': 'iso-8859-6', + 'csisolatinarabic': 'iso-8859-6', + 'ecma-114': 'iso-8859-6', + 'iso-8859-6': 'iso-8859-6', + 'iso-8859-6-e': 'iso-8859-6', + 'iso-8859-6-i': 'iso-8859-6', + 'iso-ir-127': 'iso-8859-6', + 'iso8859-6': 'iso-8859-6', + 'iso88596': 'iso-8859-6', + 'iso_8859-6': 'iso-8859-6', + 'iso_8859-6:1987': 'iso-8859-6', + 'csisolatingreek': 'iso-8859-7', + 'ecma-118': 'iso-8859-7', + 'elot_928': 'iso-8859-7', + 'greek': 'iso-8859-7', + 'greek8': 'iso-8859-7', + 'iso-8859-7': 'iso-8859-7', + 'iso-ir-126': 'iso-8859-7', + 'iso8859-7': 'iso-8859-7', + 'iso88597': 'iso-8859-7', + 'iso_8859-7': 'iso-8859-7', + 'iso_8859-7:1987': 'iso-8859-7', + 'sun_eu_greek': 'iso-8859-7', + 'csiso88598e': 'iso-8859-8', + 'csisolatinhebrew': 'iso-8859-8', + 'hebrew': 'iso-8859-8', + 'iso-8859-8': 'iso-8859-8', + 'iso-8859-8-e': 'iso-8859-8', + 'iso-ir-138': 'iso-8859-8', + 'iso8859-8': 'iso-8859-8', + 'iso88598': 'iso-8859-8', + 'iso_8859-8': 'iso-8859-8', + 'iso_8859-8:1988': 'iso-8859-8', + 'visual': 'iso-8859-8', + 'csiso88598i': 'iso-8859-8-i', + 'iso-8859-8-i': 'iso-8859-8-i', + 'logical': 'iso-8859-8-i', + 'csisolatin6': 'iso-8859-10', + 'iso-8859-10': 'iso-8859-10', + 'iso-ir-157': 'iso-8859-10', + 'iso8859-10': 'iso-8859-10', + 'iso885910': 'iso-8859-10', + 'l6': 'iso-8859-10', + 'latin6': 'iso-8859-10', + 'iso-8859-13': 'iso-8859-13', + 'iso8859-13': 'iso-8859-13', + 'iso885913': 'iso-8859-13', + 'iso-8859-14': 'iso-8859-14', + 'iso8859-14': 'iso-8859-14', + 'iso885914': 'iso-8859-14', + 'csisolatin9': 'iso-8859-15', + 'iso-8859-15': 'iso-8859-15', + 'iso8859-15': 'iso-8859-15', + 'iso885915': 'iso-8859-15', + 'iso_8859-15': 'iso-8859-15', + 'l9': 'iso-8859-15', + 'iso-8859-16': 'iso-8859-16', + 'cskoi8r': 'koi8-r', + 'koi': 'koi8-r', + 'koi8': 'koi8-r', + 'koi8-r': 'koi8-r', + 'koi8_r': 'koi8-r', + 'koi8-u': 'koi8-u', + 'csmacintosh': 'macintosh', + 'mac': 'macintosh', + 'macintosh': 'macintosh', + 'x-mac-roman': 'macintosh', + 'dos-874': 'windows-874', + 'iso-8859-11': 'windows-874', + 'iso8859-11': 'windows-874', + 'iso885911': 'windows-874', + 'tis-620': 'windows-874', + 'windows-874': 'windows-874', + 'cp1250': 'windows-1250', + 'windows-1250': 'windows-1250', + 'x-cp1250': 'windows-1250', + 'cp1251': 'windows-1251', + 'windows-1251': 'windows-1251', + 'x-cp1251': 'windows-1251', + 'ansi_x3.4-1968': 'windows-1252', + 'ascii': 'windows-1252', + 'cp1252': 'windows-1252', + 'cp819': 'windows-1252', + 'csisolatin1': 'windows-1252', + 'ibm819': 'windows-1252', + 'iso-8859-1': 'windows-1252', + 'iso-ir-100': 'windows-1252', + 'iso8859-1': 'windows-1252', + 'iso88591': 'windows-1252', + 'iso_8859-1': 'windows-1252', + 'iso_8859-1:1987': 'windows-1252', + 'l1': 'windows-1252', + 'latin1': 'windows-1252', + 'us-ascii': 'windows-1252', + 'windows-1252': 'windows-1252', + 'x-cp1252': 'windows-1252', + 'cp1253': 'windows-1253', + 'windows-1253': 'windows-1253', + 'x-cp1253': 'windows-1253', + 'cp1254': 'windows-1254', + 'csisolatin5': 'windows-1254', + 'iso-8859-9': 'windows-1254', + 'iso-ir-148': 'windows-1254', + 'iso8859-9': 'windows-1254', + 'iso88599': 'windows-1254', + 'iso_8859-9': 'windows-1254', + 'iso_8859-9:1989': 'windows-1254', + 'l5': 'windows-1254', + 'latin5': 'windows-1254', + 'windows-1254': 'windows-1254', + 'x-cp1254': 'windows-1254', + 'cp1255': 'windows-1255', + 'windows-1255': 'windows-1255', + 'x-cp1255': 'windows-1255', + 'cp1256': 'windows-1256', + 'windows-1256': 'windows-1256', + 'x-cp1256': 'windows-1256', + 'cp1257': 'windows-1257', + 'windows-1257': 'windows-1257', + 'x-cp1257': 'windows-1257', + 'cp1258': 'windows-1258', + 'windows-1258': 'windows-1258', + 'x-cp1258': 'windows-1258', + 'x-mac-cyrillic': 'x-mac-cyrillic', + 'x-mac-ukrainian': 'x-mac-cyrillic', + 'chinese': 'gbk', + 'csgb2312': 'gbk', + 'csiso58gb231280': 'gbk', + 'gb2312': 'gbk', + 'gb_2312': 'gbk', + 'gb_2312-80': 'gbk', + 'gbk': 'gbk', + 'iso-ir-58': 'gbk', + 'x-gbk': 'gbk', + 'gb18030': 'gb18030', + 'hz-gb-2312': 'hz-gb-2312', + 'big5': 'big5', + 'big5-hkscs': 'big5', + 'cn-big5': 'big5', + 'csbig5': 'big5', + 'x-x-big5': 'big5', + 'cseucpkdfmtjapanese': 'euc-jp', + 'euc-jp': 'euc-jp', + 'x-euc-jp': 'euc-jp', + 'csiso2022jp': 'iso-2022-jp', + 'iso-2022-jp': 'iso-2022-jp', + 'csshiftjis': 'shift_jis', + 'ms_kanji': 'shift_jis', + 'shift-jis': 'shift_jis', + 'shift_jis': 'shift_jis', + 'sjis': 'shift_jis', + 'windows-31j': 'shift_jis', + 'x-sjis': 'shift_jis', + 'cseuckr': 'euc-kr', + 'csksc56011987': 'euc-kr', + 'euc-kr': 'euc-kr', + 'iso-ir-149': 'euc-kr', + 'korean': 'euc-kr', + 'ks_c_5601-1987': 'euc-kr', + 'ks_c_5601-1989': 'euc-kr', + 'ksc5601': 'euc-kr', + 'ksc_5601': 'euc-kr', + 'windows-949': 'euc-kr', + 'csiso2022kr': 'iso-2022-kr', + 'iso-2022-kr': 'iso-2022-kr', + 'utf-16be': 'utf-16be', + 'utf-16': 'utf-16le', + 'utf-16le': 'utf-16le', + 'x-user-defined': 'x-user-defined', +} diff --git a/pip/_vendor/webencodings/mklabels.py b/pip/_vendor/webencodings/mklabels.py new file mode 100644 --- /dev/null +++ b/pip/_vendor/webencodings/mklabels.py @@ -0,0 +1,59 @@ +""" + + webencodings.mklabels + ~~~~~~~~~~~~~~~~~~~~~ + + Regenarate the webencodings.labels module. + + :copyright: Copyright 2012 by Simon Sapin + :license: BSD, see LICENSE for details. + +""" + +import json +try: + from urllib import urlopen +except ImportError: + from urllib.request import urlopen + + +def assert_lower(string): + assert string == string.lower() + return string + + +def generate(url): + parts = ['''\ +""" + + webencodings.labels + ~~~~~~~~~~~~~~~~~~~ + + Map encoding labels to their name. + + :copyright: Copyright 2012 by Simon Sapin + :license: BSD, see LICENSE for details. + +""" + +# XXX Do not edit! +# This file is automatically generated by mklabels.py + +LABELS = { +'''] + labels = [ + (repr(assert_lower(label)).lstrip('u'), + repr(encoding['name']).lstrip('u')) + for category in json.loads(urlopen(url).read().decode('ascii')) + for encoding in category['encodings'] + for label in encoding['labels']] + max_len = max(len(label) for label, name in labels) + parts.extend( + ' %s:%s %s,\n' % (label, ' ' * (max_len - len(label)), name) + for label, name in labels) + parts.append('}') + return ''.join(parts) + + +if __name__ == '__main__': + print(generate('http://encoding.spec.whatwg.org/encodings.json')) diff --git a/pip/_vendor/webencodings/x_user_defined.py b/pip/_vendor/webencodings/x_user_defined.py new file mode 100644 --- /dev/null +++ b/pip/_vendor/webencodings/x_user_defined.py @@ -0,0 +1,325 @@ +# coding: utf8 +""" + + webencodings.x_user_defined + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + An implementation of the x-user-defined encoding. + + :copyright: Copyright 2012 by Simon Sapin + :license: BSD, see LICENSE for details. + +""" + +from __future__ import unicode_literals + +import codecs + + +### Codec APIs + +class Codec(codecs.Codec): + + def encode(self, input, errors='strict'): + return codecs.charmap_encode(input, errors, encoding_table) + + def decode(self, input, errors='strict'): + return codecs.charmap_decode(input, errors, decoding_table) + + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input, final=False): + return codecs.charmap_encode(input, self.errors, encoding_table)[0] + + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return codecs.charmap_decode(input, self.errors, decoding_table)[0] + + +class StreamWriter(Codec, codecs.StreamWriter): + pass + + +class StreamReader(Codec, codecs.StreamReader): + pass + + +### encodings module API + +codec_info = codecs.CodecInfo( + name='x-user-defined', + encode=Codec().encode, + decode=Codec().decode, + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamreader=StreamReader, + streamwriter=StreamWriter, +) + + +### Decoding Table + +# Python 3: +# for c in range(256): print(' %r' % chr(c if c < 128 else c + 0xF700)) +decoding_table = ( + '\x00' + '\x01' + '\x02' + '\x03' + '\x04' + '\x05' + '\x06' + '\x07' + '\x08' + '\t' + '\n' + '\x0b' + '\x0c' + '\r' + '\x0e' + '\x0f' + '\x10' + '\x11' + '\x12' + '\x13' + '\x14' + '\x15' + '\x16' + '\x17' + '\x18' + '\x19' + '\x1a' + '\x1b' + '\x1c' + '\x1d' + '\x1e' + '\x1f' + ' ' + '!' + '"' + '#' + '$' + '%' + '&' + "'" + '(' + ')' + '*' + '+' + ',' + '-' + '.' + '/' + '0' + '1' + '2' + '3' + '4' + '5' + '6' + '7' + '8' + '9' + ':' + ';' + '<' + '=' + '>' + '?' + '@' + 'A' + 'B' + 'C' + 'D' + 'E' + 'F' + 'G' + 'H' + 'I' + 'J' + 'K' + 'L' + 'M' + 'N' + 'O' + 'P' + 'Q' + 'R' + 'S' + 'T' + 'U' + 'V' + 'W' + 'X' + 'Y' + 'Z' + '[' + '\\' + ']' + '^' + '_' + '`' + 'a' + 'b' + 'c' + 'd' + 'e' + 'f' + 'g' + 'h' + 'i' + 'j' + 'k' + 'l' + 'm' + 'n' + 'o' + 'p' + 'q' + 'r' + 's' + 't' + 'u' + 'v' + 'w' + 'x' + 'y' + 'z' + '{' + '|' + '}' + '~' + '\x7f' + '\uf780' + '\uf781' + '\uf782' + '\uf783' + '\uf784' + '\uf785' + '\uf786' + '\uf787' + '\uf788' + '\uf789' + '\uf78a' + '\uf78b' + '\uf78c' + '\uf78d' + '\uf78e' + '\uf78f' + '\uf790' + '\uf791' + '\uf792' + '\uf793' + '\uf794' + '\uf795' + '\uf796' + '\uf797' + '\uf798' + '\uf799' + '\uf79a' + '\uf79b' + '\uf79c' + '\uf79d' + '\uf79e' + '\uf79f' + '\uf7a0' + '\uf7a1' + '\uf7a2' + '\uf7a3' + '\uf7a4' + '\uf7a5' + '\uf7a6' + '\uf7a7' + '\uf7a8' + '\uf7a9' + '\uf7aa' + '\uf7ab' + '\uf7ac' + '\uf7ad' + '\uf7ae' + '\uf7af' + '\uf7b0' + '\uf7b1' + '\uf7b2' + '\uf7b3' + '\uf7b4' + '\uf7b5' + '\uf7b6' + '\uf7b7' + '\uf7b8' + '\uf7b9' + '\uf7ba' + '\uf7bb' + '\uf7bc' + '\uf7bd' + '\uf7be' + '\uf7bf' + '\uf7c0' + '\uf7c1' + '\uf7c2' + '\uf7c3' + '\uf7c4' + '\uf7c5' + '\uf7c6' + '\uf7c7' + '\uf7c8' + '\uf7c9' + '\uf7ca' + '\uf7cb' + '\uf7cc' + '\uf7cd' + '\uf7ce' + '\uf7cf' + '\uf7d0' + '\uf7d1' + '\uf7d2' + '\uf7d3' + '\uf7d4' + '\uf7d5' + '\uf7d6' + '\uf7d7' + '\uf7d8' + '\uf7d9' + '\uf7da' + '\uf7db' + '\uf7dc' + '\uf7dd' + '\uf7de' + '\uf7df' + '\uf7e0' + '\uf7e1' + '\uf7e2' + '\uf7e3' + '\uf7e4' + '\uf7e5' + '\uf7e6' + '\uf7e7' + '\uf7e8' + '\uf7e9' + '\uf7ea' + '\uf7eb' + '\uf7ec' + '\uf7ed' + '\uf7ee' + '\uf7ef' + '\uf7f0' + '\uf7f1' + '\uf7f2' + '\uf7f3' + '\uf7f4' + '\uf7f5' + '\uf7f6' + '\uf7f7' + '\uf7f8' + '\uf7f9' + '\uf7fa' + '\uf7fb' + '\uf7fc' + '\uf7fd' + '\uf7fe' + '\uf7ff' +) + +### Encoding table +encoding_table = codecs.charmap_build(decoding_table) diff --git a/pip/index.py b/pip/index.py --- a/pip/index.py +++ b/pip/index.py @@ -727,7 +727,7 @@ def __init__(self, content, url, headers=None): self.content = content self.parsed = html5lib.parse( self.content, - encoding=encoding, + transport_encoding=encoding, namespaceHTMLElements=False, ) self.url = url
pip fails to install projects with console entry points on Python 3.6 - Pip version: 8.1.2 - Python version: 3.6b0 - Operating System: Windows 7 ``` >py -m pip --version pip 8.1.2 from C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages (python 3.6) ``` ### Description: This appears to happen for any package with console entry points, but not for packages without. It looks like a distlib bug, so it will need fixing there and revendoring. Further note, this issue seems to affect `python -m pip install -U pip` so we'll need to consider how to help users to upgrade past this issue. (Simplest way may be to recommend that users uninstall pip and then use `get-pip.py`). ### What I've run: ``` >py -m pip install invoke Collecting invoke Using cached invoke-0.13.0-py3-none-any.whl Installing collected packages: invoke Exception: Traceback (most recent call last): File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\commands\install.py", line 317, in run prefix=options.prefix_path, File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_set.py", line 742, in install **kwargs File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_install.py", line 831, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files isolated=self.isolated, File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\wheel.py", line 493, in move_wheel_files maker.make_multiple(['%s = %s' % kv for kv in console.items()]) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 383, in make_multiple filenames.extend(self.make(specification, options)) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 372, in make self._make_script(entry, filenames, options=options) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 276, in _make_script self._write_script(scriptnames, shebang, script, filenames, ext) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 212, in _write_script launcher = self._get_launcher('t') File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 351, in _get_launcher result = finder(distlib_package).find(name).bytes File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\resources.py", line 324, in finder raise DistlibException('Unable to locate finder for %r' % package) pip._vendor.distlib.DistlibException: Unable to locate finder for 'pip._vendor.distlib' ``` Presumably this is distlib issue https://bitbucket.org/pypa/distlib/issues/87/resource-finder-looking-at-wrong-module - is that correct @zooba?
Just to be clear, assuming this is a distlib issue, there's no immediate action needed for pip. I raised this issue mainly as a reminder that we need to get a fix out relatively quickly once the distlib issue is resolved, as the problem makes it particularly hard for users to test the new Python 3.6 release. Yep, that's the issue. I was just coming over here to link to it :) Do you know of any env var or CLI option to skip entry points? I couldn't find anything quickly scanning the docs and code Not offhand, unfortunately. Looks like Vinay just resolved the issue. It would be nice to get pip updated too. We'll need @vsajip to release a new version of distlib, which we can then vendor. I'm happy to do the re-vendor but I can't produce a pip release. @dstufft would we be able to do a quick pip release for this? Without an easy way to disable scripts, allowing an upgrade, maybe this would be worth a fixed Python 3.6b1 Windows binary with the updated pip in it? Unfortunately, that wouldn't _just_ be the distlib fix, so it may not be a good idea to have pip different in the Linux and Windows builds. Hi. I get a " 'pip' has no attribute 'get installed distributions'" (on3.6.0b1-amd64 win10). is it same sort of issue or a new one ? found the/my error : my install process was doing a "python -m pip install --upgrade --force-reinstall pip" that ends badly when pip version is unchanged. Sorry for the noise ... patching resources.py doesn't seem to be enough tp resolve the issue, for Winpython at least, as I get now the same initial error as pfmoore. Guido unequivocally stated last week that quick fixes like that should up the version number, and I'm inclined to agree. I think uninstalling and running get-pip.py is not unreasonable. @stonebig I think your install is corrupt - have you tried repairing it? @stonebig Doesn't sound like it, but could you give more details (how you invoked pip, etc). I presume this is with 3.6b1 - is it with the pip shipped with that or with master? @zooba Sounds reasonable, like you say a one-off get-pip isn't that onerous for people running the beta. [Python 3.6.0b1 (64-bit)_20160913185823.log.txt](https://github.com/pypa/pip/files/470362/Python.3.6.0b1.64-bit._20160913185823.log.txt) the message is on the "zipped" result. for what is in the "installed programs", it propose me to install it when I click on "uninstall" (only option), and I get the attached log idle works, on the winpython3.6 beta directory, so things are not an absolute fail. @pfmoore Except I did just try `py get-pip.py` and it tried to install into the wrong Python (i.e. a different one than `py` runs with). Probably a launcher bug... @stonebig I think we need you to write up the step-by-step list of everything you did and post it on https://bugs.python.org/. I'm fairly convinced your issues are not bugs in CPython or pip, but they may be an installer issue. Without specific steps and the download URLs you used, I can't make any better guesses. @zooba `get-pip.py` has a shebang of `#!/usr/bin/env python`. That's going to run whatever Python command you have on your PATH by default. Did you perchance not have Python 3.6 on PATH at the time? https://bugs.python.org/issue28132 1- I did the zooba style of install of python3.6, to get a zippable thing, 2- after the zip creation for winpython , i went to the "Applications and functionnality" panel of windows 10 and tried to uninstall. the uninstall button showed me the install door only ... about 5 times out of 6. I'm windows10-10586.545 (not upgraded to summer 2016 yet) ok, by clicking on the ".exe" installer, I succeeded to repair, then via "application and functionalities menu" uninstall started the right way, finished happy of itself ... without uninstalling from "applications and functionalities". clicking again on the installer (instead of application and functionnalities) did at last the job of uninstalling http://stackoverflow.com/questions/39908406/unable-to-locate-finder-for-pip-vendor-distlib-error-when-using-pip-instal Running into this issue :( I assume the fix is in the recently released distlib 0.2.4, so we should revendor. (Probably better if someone on Unix does this, IIRC git gets confused over line endings if I do it on Windows :-() Yes, it's in 0.2.4 (listed under "Resources" at https://goo.gl/M3kQzR)
2016-10-29T16:01:02Z
[]
[]
Traceback (most recent call last): File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\commands\install.py", line 317, in run prefix=options.prefix_path, File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_set.py", line 742, in install **kwargs File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_install.py", line 831, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files isolated=self.isolated, File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\wheel.py", line 493, in move_wheel_files maker.make_multiple(['%s = %s' % kv for kv in console.items()]) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 383, in make_multiple filenames.extend(self.make(specification, options)) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 372, in make self._make_script(entry, filenames, options=options) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 276, in _make_script self._write_script(scriptnames, shebang, script, filenames, ext) File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 212, in _write_script launcher = self._get_launcher('t') File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 351, in _get_launcher result = finder(distlib_package).find(name).bytes File "C:\Users\UK03306\AppData\Local\Programs\Python\Python36\lib\site-packages\pip\_vendor\distlib\resources.py", line 324, in finder raise DistlibException('Unable to locate finder for %r' % package) pip._vendor.distlib.DistlibException: Unable to locate finder for 'pip._vendor.distlib'
17,314
pypa/pip
pypa__pip-4044
3f29ad305a6e6d84d479620304045a0fd235ef71
diff --git a/pip/commands/search.py b/pip/commands/search.py --- a/pip/commands/search.py +++ b/pip/commands/search.py @@ -5,6 +5,7 @@ import textwrap from pip.basecommand import Command, SUCCESS +from pip.compat import OrderedDict from pip.download import PipXmlrpcTransport from pip.models import PyPI from pip.utils import get_terminal_size @@ -68,21 +69,17 @@ def transform_hits(hits): packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ - packages = {} + packages = OrderedDict() for hit in hits: name = hit['name'] summary = hit['summary'] version = hit['version'] - score = hit['_pypi_ordering'] - if score is None: - score = 0 if name not in packages.keys(): packages[name] = { 'name': name, 'summary': summary, 'versions': [version], - 'score': score, } else: packages[name]['versions'].append(version) @@ -90,16 +87,8 @@ def transform_hits(hits): # if this is the highest version, replace summary and score if version == highest_version(packages[name]['versions']): packages[name]['summary'] = summary - 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, - ) - return package_list + + return list(packages.values()) def print_results(hits, name_column_width=None, terminal_width=None):
KeyError: '_pypi_ordering' when using new Pypi warehouse site with 'pip search' - Pip version: 8.1.2 - Python version: 2.7.6 - Operating System: Ubuntu 14.04 ### Description: As discussed in issue #3767 and in IRC channel #pypa-dev, the pip command should work against the new Pypi warehouse site when using the `--index` option with the URL `https://pypi.io/pypi`. However I did not get it to work. See below. ### What I've run: ``` $ pip search --index https://pypi.io/pypi GitPython Exception: Traceback (most recent call last): File "/home/maiera/virtualenvs/pywbem27/local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/maiera/virtualenvs/pywbem27/local/lib/python2.7/site-packages/pip/commands/search.py", line 44, in run hits = transform_hits(pypi_hits) File "/home/maiera/virtualenvs/pywbem27/local/lib/python2.7/site-packages/pip/commands/search.py", line 75, in transform_hits score = hit['_pypi_ordering'] KeyError: '_pypi_ordering' ```
2016-10-30T15:55:36Z
[]
[]
Traceback (most recent call last): File "/home/maiera/virtualenvs/pywbem27/local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/maiera/virtualenvs/pywbem27/local/lib/python2.7/site-packages/pip/commands/search.py", line 44, in run hits = transform_hits(pypi_hits) File "/home/maiera/virtualenvs/pywbem27/local/lib/python2.7/site-packages/pip/commands/search.py", line 75, in transform_hits score = hit['_pypi_ordering'] KeyError: '_pypi_ordering'
17,316
pypa/pip
pypa__pip-4046
765d52e6bd33271382663111f19d235b83320363
diff --git a/pip/operations/freeze.py b/pip/operations/freeze.py --- a/pip/operations/freeze.py +++ b/pip/operations/freeze.py @@ -5,6 +5,7 @@ import pip from pip.req import InstallRequirement +from pip.req.req_file import COMMENT_RE from pip.utils import get_installed_distributions from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name @@ -96,7 +97,7 @@ def freeze( ) else: line_req = InstallRequirement.from_line( - line, + COMMENT_RE.sub('', line).strip(), isolated=isolated, wheel_cache=wheel_cache, ) @@ -115,7 +116,7 @@ def freeze( logger.warning( "Requirement file [%s] contains %s, but that " "package is not installed", - req_file_path, line.strip(), + req_file_path, COMMENT_RE.sub('', line).strip(), ) else: yield str(installations[line_req.name]).rstrip()
pip freeze --requirement doesn't accept inline comments - Pip version: 8.1.2 - Python version: 2.7.11 - Operating System: Mac OS X ### Description: pip freeze --requirement doesn't accept inline comments ### What I've run: ``` pip freeze -r requirements.txt ``` Output: ``` Invalid requirement: 'alembic==0.8.6 # MIT license' Traceback (most recent call last): File ".../site-packages/pip/req/req_install.py", line 78, in __init__ req = Requirement(req) File ".../site-packages/pip/_vendor/packaging/requirements.py", line 96, in __init__ requirement_string[e.loc:e.loc + 8])) InvalidRequirement: Invalid requirement, parse error at "'# MIT li'" ``` requirements.txt: ``` alembic==0.8.6 # MIT license Babel==2.3.4 # BSD license ``` `pip install -r` works for this requirements.txt file. Documentation states: > Whitespace followed by a # causes the # and the remainder of the line to be treated as a comment.
Just confirmed that pip version 8.1.1 doesn't have this bug
2016-10-30T19:56:42Z
[]
[]
Traceback (most recent call last): File ".../site-packages/pip/req/req_install.py", line 78, in __init__ req = Requirement(req) File ".../site-packages/pip/_vendor/packaging/requirements.py", line 96, in __init__ requirement_string[e.loc:e.loc + 8])) InvalidRequirement: Invalid requirement, parse error at "'# MIT li'"
17,317
pypa/pip
pypa__pip-4067
382a7e111be499195c1b3321ff6d649c34605992
diff --git a/pip/_vendor/distro.py b/pip/_vendor/distro.py --- a/pip/_vendor/distro.py +++ b/pip/_vendor/distro.py @@ -589,12 +589,14 @@ def __init__(self, self.os_release_file = os_release_file or \ os.path.join(_UNIXCONFDIR, _OS_RELEASE_BASENAME) self.distro_release_file = distro_release_file or '' # updated later - self._os_release_info = self._os_release_info() - self._lsb_release_info = self._lsb_release_info() \ + self._os_release_info = self._get_os_release_info() + self._lsb_release_info = self._get_lsb_release_info() \ if include_lsb else {} - self._distro_release_info = self._distro_release_info() + self._distro_release_info = self._get_distro_release_info() def __repr__(self): + """Return repr of all info + """ return \ "LinuxDistribution(" \ "os_release_file={0!r}, " \ @@ -623,12 +625,10 @@ def linux_distribution(self, full_distribution_name=True): ) def id(self): - """ - Return the distro ID of the Linux distribution, as a string. + """Return the distro ID of the Linux distribution, as a string. For details, see :func:`distro.id`. """ - def normalize(distro_id, table): distro_id = distro_id.lower().replace(' ', '_') return table.get(distro_id, distro_id) @@ -833,7 +833,7 @@ def distro_release_attr(self, attribute): """ return self._distro_release_info.get(attribute, '') - def _os_release_info(self): + def _get_os_release_info(self): """ Get the information items from the specified os-release file. @@ -905,7 +905,7 @@ def _parse_os_release_content(lines): pass return props - def _lsb_release_info(self): + def _get_lsb_release_info(self): """ Get the information items from the lsb_release command output. @@ -919,7 +919,7 @@ def _lsb_release_info(self): stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() - stdout, stderr = stdout.decode('ascii'), stderr.decode('ascii') + stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8') code = process.returncode if code == 0: content = stdout.splitlines() @@ -950,8 +950,7 @@ def _parse_lsb_release_content(lines): """ props = {} for line in lines: - if isinstance(line, bytes): - line = line.decode('utf-8') + line = line.decode('utf-8') if isinstance(line, bytes) else line kv = line.strip('\n').split(':', 1) if len(kv) != 2: # Ignore lines without colon. @@ -960,7 +959,7 @@ def _parse_lsb_release_content(lines): props.update({k.replace(' ', '_').lower(): v.strip()}) return props - def _distro_release_info(self): + def _get_distro_release_info(self): """ Get the information items from the specified distro release file. @@ -1067,15 +1066,15 @@ def main(): args = parser.parse_args() if args.json: - logger.info(json.dumps(info())) + logger.info(json.dumps(info(), indent=4, sort_keys=True)) else: - logger.info('Name: {0}'.format(name(pretty=True))) + logger.info('Name: %s', name(pretty=True)) distribution_version = version(pretty=True) if distribution_version: - logger.info('Version: {0}'.format(distribution_version)) + logger.info('Version: %s', distribution_version) distribution_codename = codename() if distribution_codename: - logger.info('Codename: {0}'.format(distribution_codename)) + logger.info('Codename: %s', distribution_codename) if __name__ == '__main__':
Pip crashes on non-ASCII symbol in lsb_release output * Pip version: 9.0.0 * Python version: CPython 3.5.2 * Operating System: Fedora release 19 (Schrödinger’s Cat) ### Description: According to https://github.com/pypa/pip/blob/c8e8a99b7a6f9404536bc9d895a1a42a060f7f91/pip/_vendor/distro.py#L922 pip wants ```lsb_release -a``` output to be strictly in ascii only, while there can be any unicode symbol. Because of that it crashes on ```Fedora release 19 (Schrödinger’s Cat)``` with traceback ``` Traceback (most recent call last): File "/home/username/.virtualenvs/powerdns-cpython3.5/bin/pip", line 11, in <module> sys.exit(main()) File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as session: File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/download.py", line 93, in user_agent from pip._vendor import distro File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/_vendor/distro.py", line 1051, in <module> _distro = LinuxDistribution() File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/_vendor/distro.py", line 594, in __init__ if include_lsb else {} File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/_vendor/distro.py", line 922, in _lsb_release_info stdout, stderr = stdout.decode('ascii'), stderr.decode('ascii') UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 250: ordinal not in range(128) ``` ### What I've run: ```sh pip install . ```
Fixed in distro module in https://github.com/nir0s/distro/pull/144
2016-11-03T11:06:50Z
[]
[]
Traceback (most recent call last): File "/home/username/.virtualenvs/powerdns-cpython3.5/bin/pip", line 11, in <module> sys.exit(main()) File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as session: File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/download.py", line 93, in user_agent from pip._vendor import distro File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/_vendor/distro.py", line 1051, in <module> _distro = LinuxDistribution() File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/_vendor/distro.py", line 594, in __init__ if include_lsb else {} File "/home/username/.virtualenvs/powerdns-cpython3.5/lib/python3.5/site-packages/pip/_vendor/distro.py", line 922, in _lsb_release_info stdout, stderr = stdout.decode('ascii'), stderr.decode('ascii') UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 250: ordinal not in range(128)
17,320
pypa/pip
pypa__pip-4071
382a7e111be499195c1b3321ff6d649c34605992
diff --git a/pip/index.py b/pip/index.py --- a/pip/index.py +++ b/pip/index.py @@ -1036,16 +1036,6 @@ def is_artifact(self): return True - def normalize(self): - parsed = urllib_parse.urlsplit(self.url) - if parsed.scheme == 'file': - path = urllib_request.url2pathname(parsed.path) - path = normalize_path(path) - path = urllib_request.pathname2url(path) - self.url = urllib_parse.urlunsplit( - (parsed.scheme, parsed.netloc, - path, parsed.query, parsed.fragment)) - FormatControl = namedtuple('FormatControl', 'no_binary only_binary') """This object has two fields, no_binary and only_binary. diff --git a/pip/req/req_install.py b/pip/req/req_install.py --- a/pip/req/req_install.py +++ b/pip/req/req_install.py @@ -212,8 +212,10 @@ def from_line( # it's a local file, dir, or url if link: - # Normalize URLs - link.normalize() + # Handle relative file URLs + if link.scheme == 'file' and re.search(r'\.\./', link.url): + link = Link( + path_to_url(os.path.normpath(os.path.abspath(link.path)))) # wheel file if link.is_wheel: wheel = Wheel(link.filename) # can raise InvalidWheelFilename
pip 9.0 cannot parse UNC paths. * Pip version: 9.0 * Python version: 2.7.2 * Operating System: Windows 10 ### Description: I'm trying to install a wheel I've prepared on a UNC share. This works with pip 8.1.2 but not with pip 9.0 ### What I've run: With pip 8.1.2: ``` pip install \\<UNC path>\<package>.whl [...] Successfully installed <package> ``` With pip 9.0: ``` pip install \\<UNC path>\<package>.whl Exception: Traceback (most recent call last): File "d:\venv\pip9\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "d:\venv\pip9\lib\site-packages\pip\commands\install.py", line 335, in run wb.build(autobuilding=True) File "d:\venv\pip9\lib\site-packages\pip\wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "d:\venv\pip9\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "d:\venv\pip9\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "d:\venv\pip9\lib\site-packages\pip\download.py", line 809, in unpack_url unpack_file_url(link, location, download_dir, hashes=hashes) File "d:\venv\pip9\lib\site-packages\pip\download.py", line 715, in unpack_file_url unpack_file(from_path, location, content_type, link) File "d:\venv\pip9\lib\site-packages\pip\utils\__init__.py", line 599, in unpack_file flatten=not filename.endswith('.whl') File "d:\venv\pip9\lib\site-packages\pip\utils\__init__.py", line 482, in unzip_file zipfp = open(filename, 'rb') IOError: [Errno 2] No such file or directory: 'D:\\<UNC path>\\<package>.whl' ```
The UNC path syntax seems wrong - it should be `\\server\share\path\to\file` (double backslash at the start). Was that a typo in your report? If not, could you try the correct syntax and confirm if the problem occurs with that? That was just due to missing code tags, thanks for pointing it out. I don't know anything about UNC on Windows. @pfmoore is this something we should get fixed in a 9.0.1? @dstufft It's a regression from 8.1.2 (just tested it here). I've no immediate feel for how many people this could affect, but I'd be inclined to say it's worth fixing quickly. I'll do some quick checking to see if I can locate the source of the problem, but I don't have a feel yet for how easy a fix will be. Okay added to 9.0.1 milestone, but I'm probably not personally going to be able to fix it since I don't really know much about UNC on Windows :( OK. Bisect found the issue - introduced by 84c969669c0242c9e70137312b7d1001b4af26f8 (PR #3724). As a quick resolution, I recommend that we revert that commit. It looks like `urllib` might be doing funky things with UNC paths, and I don't really have the time to dig into that right now... Seems like a reasonable idea to me, do you want to do that @pfmoore or want me to? If you have the time, I'd appreciate it. My git skills are limited and I'd rather not risk breaking anything.
2016-11-03T12:30:04Z
[]
[]
Traceback (most recent call last): File "d:\venv\pip9\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "d:\venv\pip9\lib\site-packages\pip\commands\install.py", line 335, in run wb.build(autobuilding=True) File "d:\venv\pip9\lib\site-packages\pip\wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "d:\venv\pip9\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "d:\venv\pip9\lib\site-packages\pip\req\req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "d:\venv\pip9\lib\site-packages\pip\download.py", line 809, in unpack_url unpack_file_url(link, location, download_dir, hashes=hashes) File "d:\venv\pip9\lib\site-packages\pip\download.py", line 715, in unpack_file_url unpack_file(from_path, location, content_type, link) File "d:\venv\pip9\lib\site-packages\pip\utils\__init__.py", line 599, in unpack_file flatten=not filename.endswith('.whl') File "d:\venv\pip9\lib\site-packages\pip\utils\__init__.py", line 482, in unzip_file zipfp = open(filename, 'rb') IOError: [Errno 2] No such file or directory: 'D:\\<UNC path>\\<package>.whl'
17,323
pypa/pip
pypa__pip-4352
cee7a53712d2cfdcc544da58e41cf688e974e576
diff --git a/pip/_vendor/distro.py b/pip/_vendor/distro.py --- a/pip/_vendor/distro.py +++ b/pip/_vendor/distro.py @@ -61,7 +61,8 @@ #: * Value: Normalized value. NORMALIZED_LSB_ID = { 'enterpriseenterprise': 'oracle', # Oracle Enterprise Linux - 'redhatenterpriseworkstation': 'rhel', # RHEL 6.7 + 'redhatenterpriseworkstation': 'rhel', # RHEL 6, 7 Workstation + 'redhatenterpriseserver': 'rhel', # RHEL 6, 7 Server } #: Translation table for normalizing the distro ID derived from the file name @@ -1011,12 +1012,16 @@ def _parse_distro_release_file(self, filepath): Returns: A dictionary containing all information items. """ - if os.path.isfile(filepath): + try: with open(filepath) as fp: # Only parse the first line. For instance, on SLES there # are multiple lines. We don't want them... return self._parse_distro_release_content(fp.readline()) - return {} + except (OSError, IOError): + # Ignore not being able to read a specific, seemingly version + # related file. + # See https://github.com/nir0s/distro/issues/162 + return {} @staticmethod def _parse_distro_release_content(line): @@ -1070,11 +1075,9 @@ def main(): else: logger.info('Name: %s', name(pretty=True)) distribution_version = version(pretty=True) - if distribution_version: - logger.info('Version: %s', distribution_version) + logger.info('Version: %s', distribution_version) distribution_codename = codename() - if distribution_codename: - logger.info('Codename: %s', distribution_codename) + logger.info('Codename: %s', distribution_codename) if __name__ == '__main__':
pip fails because it can't read /etc/image_version file * Pip version: 9.0.1 (Problem doesn't exist with 8.1.2) * Python version: 3.4.3 * Operating system: Ubuntu 14.04 ### Description: On my system there is a file (out of my control) named /etc/image_version . This file is NOT world-readable. When using pip 9.0.1 in one of my virtualenvs (which I expect to be "isolated" from the system) pip will crash because it can't read said file. As far as I can tell pip tries to gather some OS related information by reading all /etc/*version files. I think the PermissionError should just be catched and ignored... ### What I've run: ``` testuser@host:~$ cd tmp testuser@host:~/tmp$ virtualenv -p python3 pip-test Running virtualenv with interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in pip-test/bin/python3 Also creating executable in pip-test/bin/python Installing setuptools, pip...done. testuser@host:~/tmp$ source pip-test/bin/activate (pip-test)testuser@host:~/tmp$ pip install -U setuptools && pip install -U pip Downloading/unpacking setuptools from https://pypi.python.org/packages/52/85/15b618883d7289920943c7971b1add55188a5e4769a4f1fbec982279bcc0/setuptools-34.0.1-py2.py3-none-any.whl#md5=fa32bf7416ec1ce9df00907d4d30b2af Downloading setuptools-34.0.1-py2.py3-none-any.whl (386kB): 386kB downloaded Downloading/unpacking packaging>=16.8 (from setuptools) Downloading packaging-16.8-py2.py3-none-any.whl Downloading/unpacking six>=1.10.0 (from setuptools) Downloading six-1.10.0-py2.py3-none-any.whl Downloading/unpacking appdirs>=1.4.0 (from setuptools) Downloading appdirs-1.4.0-py2.py3-none-any.whl Downloading/unpacking pyparsing (from packaging>=16.8->setuptools) Downloading pyparsing-2.1.10-py2.py3-none-any.whl (56kB): 56kB downloaded Installing collected packages: setuptools, packaging, six, appdirs, pyparsing Found existing installation: setuptools 2.2 Uninstalling setuptools: Successfully uninstalled setuptools Successfully installed setuptools packaging six appdirs pyparsing Cleaning up... Downloading/unpacking pip from https://pypi.python.org/packages/b6/ac/7015eb97dc749283ffdec1c3a88ddb8ae03b8fad0f0e611408f196358da3/pip-9.0.1-py2.py3-none-any.whl#md5=297dbd16ef53bcef0447d245815f5144 Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB): 1.3MB downloaded Installing collected packages: pip Found existing installation: pip 1.5.4 Uninstalling pip: Successfully uninstalled pip Successfully installed pip Cleaning up... (pip-test)testuser@host:~/tmp$ pip freeze appdirs==1.4.0 packaging==16.8 pyparsing==2.1.10 six==1.10.0 Traceback (most recent call last): File "/home/testuser/tmp/pip-test/bin/pip", line 11, in <module> sys.exit(main()) File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as session: File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/download.py", line 93, in user_agent from pip._vendor import distro File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/_vendor/distro.py", line 1050, in <module> _distro = LinuxDistribution() File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/_vendor/distro.py", line 595, in __init__ self._distro_release_info = self._get_distro_release_info() File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/_vendor/distro.py", line 995, in _get_distro_release_info distro_info = self._parse_distro_release_file(filepath) File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/_vendor/distro.py", line 1015, in _parse_distro_release_file with open(filepath) as fp: PermissionError: [Errno 13] Permission denied: '/etc/image_version' ```
That looks like a bug in the "distro" package that pip vendors. I'd suggest you report it to the upstream project at https://github.com/nir0s/distro. When they release a fixed version, pip will revendor it. I'm guessing that it should be pretty simple to reproduce the problem outside of pip. I don't use Linux so I can't be sure, but at first glance at the docs, the package provides a ```distro``` command, and that command will probably also fail on your system. Yes problem can be reproduced with distro: https://github.com/nir0s/distro/issues/162 Upstream https://github.com/nir0s/distro/issues/162 has been fixed :-) (but not yet released) Upstream https://github.com/nir0s/distro/issues/162 has been released in **distro** v1.0.3
2017-03-20T15:03:46Z
[]
[]
Traceback (most recent call last): File "/home/testuser/tmp/pip-test/bin/pip", line 11, in <module> sys.exit(main()) File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as session: File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/download.py", line 329, in __init__ self.headers["User-Agent"] = user_agent() File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/download.py", line 93, in user_agent from pip._vendor import distro File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/_vendor/distro.py", line 1050, in <module> _distro = LinuxDistribution() File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/_vendor/distro.py", line 595, in __init__ self._distro_release_info = self._get_distro_release_info() File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/_vendor/distro.py", line 995, in _get_distro_release_info distro_info = self._parse_distro_release_file(filepath) File "/home/testuser/tmp/pip-test/lib/python3.4/site-packages/pip/_vendor/distro.py", line 1015, in _parse_distro_release_file with open(filepath) as fp: PermissionError: [Errno 13] Permission denied: '/etc/image_version'
17,332
pypa/pip
pypa__pip-4384
b9f70f206138d9a11158b411faf0329deb8d1d8b
diff --git a/pip/wheel.py b/pip/wheel.py --- a/pip/wheel.py +++ b/pip/wheel.py @@ -187,7 +187,7 @@ def fix_script(path): script.write(rest) return True -dist_info_re = re.compile(r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?) +dist_info_re = re.compile(r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>.+?))?) \.dist-info$""", re.VERBOSE) @@ -582,7 +582,7 @@ class Wheel(object): # TODO: maybe move the install code into this class wheel_file_re = re.compile( - r"""^(?P<namever>(?P<name>.+?)-(?P<ver>\d.*?)) + r"""^(?P<namever>(?P<name>.+?)-(?P<ver>.*?)) ((-(?P<build>\d.*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?) \.whl|\.dist-info)$""", re.VERBOSE
pip wheel should not create wheels that it will itself deem invalid * Pip version: 9.0.1 * Python version: 3.5.2 * Operating System: Arch Linux ### Description: `pip wheel` can create wheels that `pip install` will deem invalid. This should not be the case. ### What I've run: `setup.py` ``` from setuptools import setup setup(name="foo", version="!invalid!") ``` then ``` $ pip wheel . && pip install *.whl Processing /tmp/foo Building wheels for collected packages: foo Running setup.py bdist_wheel for foo ... done Stored in directory: /tmp/foo Successfully built foo foo-_invalid_-py3-none-any.whl is not a valid wheel filename. Exception information: Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python3.5/site-packages/pip/commands/install.py", line 312, in run wheel_cache File "/usr/lib/python3.5/site-packages/pip/basecommand.py", line 276, in populate_requirement_set wheel_cache=wheel_cache File "/usr/lib/python3.5/site-packages/pip/req/req_install.py", line 221, in from_line wheel = Wheel(link.filename) # can raise InvalidWheelFilename File "/usr/lib/python3.5/site-packages/pip/wheel.py", line 631, in __init__ "%s is not a valid wheel filename." % filename pip.exceptions.InvalidWheelFilename: foo-_invalid_-py3-none-any.whl is not a valid wheel filename. ``` `pip wheel` doesn't even bother to warn on the version name. As a side note, note that "interestingly", `pip install .` (installation from the directory) works just fine. As a further note, I think that internal exceptions from pip should, by default, not display a traceback.
Indeed the https://github.com/pypa/pip/blob/b559221/pip/wheel.py#L584-L588 regex seems a little too strict compared to the https://www.python.org/dev/peps/pep-0427/ requirements. The real issue being that pip should actually install this valid wheel (with a invalid/non PEP-440 version number). I don't have a preference, other than consistency.
2017-03-28T03:04:53Z
[]
[]
Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python3.5/site-packages/pip/commands/install.py", line 312, in run wheel_cache File "/usr/lib/python3.5/site-packages/pip/basecommand.py", line 276, in populate_requirement_set wheel_cache=wheel_cache File "/usr/lib/python3.5/site-packages/pip/req/req_install.py", line 221, in from_line wheel = Wheel(link.filename) # can raise InvalidWheelFilename File "/usr/lib/python3.5/site-packages/pip/wheel.py", line 631, in __init__ "%s is not a valid wheel filename." % filename pip.exceptions.InvalidWheelFilename: foo-_invalid_-py3-none-any.whl is not a valid wheel filename.
17,335
pypa/pip
pypa__pip-4495
f16de428633cfda42de9be56b4674172bce7279c
diff --git a/pip/req/req_install.py b/pip/req/req_install.py --- a/pip/req/req_install.py +++ b/pip/req/req_install.py @@ -786,9 +786,9 @@ def prepend_root(path): if os.path.isdir(filename): filename += os.path.sep new_lines.append( - os.path.relpath( - prepend_root(filename), egg_info_dir) + os.path.relpath(prepend_root(filename), egg_info_dir) ) + ensure_dir(egg_info_dir) inst_files_path = os.path.join(egg_info_dir, 'installed-files.txt') with open(inst_files_path, 'w') as f: f.write('\n'.join(new_lines) + '\n')
[pip 1.0] No such file or directory: ... installed-files.txt ``` shell # pip --version pip 1.0 from /usr/lib/python2.7/dist-packages (python 2.7) # pip install --install-option='--root=/tmp/ROOT' --install-option='--prefix=/usr' turbogears Requirement already satisfied (use --upgrade to upgrade): turbogears in /usr/lib/pymodules/python2.7 Requirement already satisfied (use --upgrade to upgrade): CherryPy>=2.3.0,<3.0dev in /usr/lib/pymodules/python2.7 (from turbogears) Requirement already satisfied (use --upgrade to upgrade): ConfigObj>=4.3.2 in /usr/lib/python2.7/dist-packages (from turbogears) Requirement already satisfied (use --upgrade to upgrade): FormEncode>=1.2.1 in /usr/lib/python2.7/dist-packages (from turbogears) Requirement already satisfied (use --upgrade to upgrade): Genshi>=0.4.4 in /usr/lib/python2.7/dist-packages (from turbogears) Requirement already satisfied (use --upgrade to upgrade): PasteScript[cheetah]>=1.7 in /usr/lib/python2.7/dist-packages (from turbogears) Requirement already satisfied (use --upgrade to upgrade): PEAK-Rules>=0.5a1.dev-r2555 in /usr/lib/pymodules/python2.7 (from turbogears) Requirement already satisfied (use --upgrade to upgrade): distribute in /usr/lib/python2.7/dist-packages (from turbogears) Requirement already satisfied (use --upgrade to upgrade): simplejson>=1.9.1 in /usr/lib/python2.7/dist-packages (from turbogears) Requirement already satisfied (use --upgrade to upgrade): TurboJson>=1.2.1 in /usr/lib/python2.7/dist-packages (from turbogears) Downloading/unpacking tgMochiKit>=1.4.2 (from turbogears) Running setup.py egg_info for package tgMochiKit Requirement already satisfied (use --upgrade to upgrade): Paste>=1.3 in /usr/lib/python2.7/dist-packages (from PasteScript[cheetah]>=1.7->turbogears) Requirement already satisfied (use --upgrade to upgrade): PasteDeploy in /usr/lib/python2.7/dist-packages (from PasteScript[cheetah]>=1.7->turbogears) Requirement already satisfied (use --upgrade to upgrade): BytecodeAssembler>=0.6 in /usr/lib/pymodules/python2.7 (from PEAK-Rules>=0.5a1.dev-r2555->turbogears) Requirement already satisfied (use --upgrade to upgrade): DecoratorTools>=1.7dev-r2450 in /usr/lib/pymodules/python2.7 (from PEAK-Rules>=0.5a1.dev-r2555->turbogears) Requirement already satisfied (use --upgrade to upgrade): AddOns>=0.6 in /usr/lib/pymodules/python2.7 (from PEAK-Rules>=0.5a1.dev-r2555->turbogears) Requirement already satisfied (use --upgrade to upgrade): Extremes>=1.1 in /usr/lib/pymodules/python2.7 (from PEAK-Rules>=0.5a1.dev-r2555->turbogears) Requirement already satisfied (use --upgrade to upgrade): SymbolType>=1.0 in /usr/lib/pymodules/python2.7 (from BytecodeAssembler>=0.6->PEAK-Rules>=0.5a1.dev-r2555->turbogears) Installing collected packages: tgMochiKit Running setup.py install for tgMochiKit Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 126, in main self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 228, in run requirement_set.install(install_options, global_options) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1093, in install requirement.install(install_options, global_options) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 593, in install f = open(os.path.join(egg_info_dir, 'installed-files.txt'), 'w') IOError: [Errno 2] No such file or directory: '/usr/lib/python2.7/site-packages/tgMochiKit-1.4.2-py2.7.egg-info/installed-files.txt' ```
I stumbled across this bug because I was also trying to use --root with pip. After searching around, I realized that I really wanted to be using --prefix instead of --root (see [Python issue 8357](http://bugs.python.org/issue8357) for a description of the difference). I thought I'd comment here in case other people were making my same mistake. Pip works as expected with --prefix. I'm going to close this since it's very old and I can't seem to reproduce. @dstufft, sounds like I'm running into exactly the same problem with latest pip on Ubuntu 14.04 with stock Python 2.7, and only when installing from git, normal instal from PyPI works just fine: ``` $ python -m pip --version pip 8.1.1 from /home/zaytsev/.local/lib/python2.7/site-packages (python 2.7) $ python -m pip install --ignore-installed --prefix lib/python-dev git+https://github.com/michaeljones/breathe.git#egg=breathe Collecting breathe from git+https://github.com/michaeljones/breathe.git#egg=breathe Cloning https://github.com/michaeljones/breathe.git to /tmp/pip-build-isU_Kb/breathe Collecting Sphinx>=1.4 (from breathe) Using cached Sphinx-1.4.1-py2.py3-none-any.whl Collecting docutils>=0.5 (from breathe) Collecting six>=1.4 (from breathe) Using cached six-1.10.0-py2.py3-none-any.whl Collecting babel!=2.0,>=1.3 (from Sphinx>=1.4->breathe) Using cached Babel-2.3.3-py2.py3-none-any.whl Collecting snowballstemmer>=1.1 (from Sphinx>=1.4->breathe) Using cached snowballstemmer-1.2.1-py2.py3-none-any.whl Collecting Pygments>=2.0 (from Sphinx>=1.4->breathe) Using cached Pygments-2.1.3-py2.py3-none-any.whl Collecting Jinja2>=2.3 (from Sphinx>=1.4->breathe) Using cached Jinja2-2.8-py2.py3-none-any.whl Collecting imagesize (from Sphinx>=1.4->breathe) Using cached imagesize-0.7.0-py2.py3-none-any.whl Collecting alabaster<0.8,>=0.7 (from Sphinx>=1.4->breathe) Using cached alabaster-0.7.7-py2.py3-none-any.whl Collecting pytz>=0a (from babel!=2.0,>=1.3->Sphinx>=1.4->breathe) Using cached pytz-2016.3-py2.py3-none-any.whl Collecting MarkupSafe (from Jinja2>=2.3->Sphinx>=1.4->breathe) Installing collected packages: pytz, babel, snowballstemmer, six, Pygments, docutils, MarkupSafe, Jinja2, imagesize, alabaster, Sphinx, breathe Running setup.py install for breathe ... done Exception: Traceback (most recent call last): File "/home/zaytsev/.local/lib/python2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/home/zaytsev/.local/lib/python2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/home/zaytsev/.local/lib/python2.7/site-packages/pip/req/req_set.py", line 732, in install **kwargs File "/home/zaytsev/.local/lib/python2.7/site-packages/pip/req/req_install.py", line 928, in install with open(inst_files_path, 'w') as f: IOError: [Errno 2] No such file or directory: 'lib/python-dev/lib/python2.7/site-packages/breathe-4.2.0-py2.7.egg-info/installed-files.txt' ``` I encountered this issue too, when installing to a `--user` with `PYTHONUSERBASE` set to a relative directory. ``` $ ls env ls: env: No such file or directory $ PYTHONUSERBASE=env python2.7 -m pip install --user genshi Collecting genshi Using cached Genshi-0.7.tar.gz Installing collected packages: genshi Running setup.py install for genshi ... done Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 732, in install **kwargs File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 928, in install with open(inst_files_path, 'w') as f: IOError: [Errno 2] No such file or directory: 'env/lib/python/site-packages/Genshi-0.7-py2.7.egg-info/installed-files.txt' $ PYTHONUSERBASE=`pwd`/env python2.7 -m pip install --user genshi Collecting genshi Using cached Genshi-0.7.tar.gz Installing collected packages: genshi Running setup.py install for genshi ... done Successfully installed genshi ``` I encounter this issue, too. Using `pip install` with the `--prefix` option. ``` Installing Python dependencies for "@niklas/nodepy-standalone-builder@0.0.1" (dev) ... Installing Python dependencies via Pip: --prefix nodepy_modules/.pip pyminifier py-blobbify Collecting pyminifier Using cached pyminifier-2.1.tar.gz Collecting py-blobbify Using cached py-blobbify-1.3.tar.gz Installing collected packages: pyminifier, py-blobbify Running setup.py install for pyminifier ... done Exception: Traceback (most recent call last): File "c:\users\niklas\applications\python35-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\niklas\applications\python35-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\users\niklas\applications\python35-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\users\niklas\applications\python35-32\lib\site-packages\pip\req\req_install.py", line 922, in install with open(inst_files_path, 'w') as f: FileNotFoundError: [Errno 2] No such file or directory: 'nodepy_modules\\.pip\\Lib\\site-packages\\pyminifier-2.1-py3.5.egg-info\\installed-files.txt' Error: `pip install` failed with exit-code 2 ``` I can reproduce this issue when using Python installed via Homebrew on macOS. ``` $ pip3.6 install -v --install-option="--prefix=nodepy_modules/.pip" werkzeug /usr/local/lib/python3.6/site-packages/pip/commands/install.py:194: UserWarning: Disabling all use of wheels due to the use of --build-options / --global-options / --install-options. cmdoptions.check_install_build_global(options) Collecting werkzeug 1 location(s) to search for versions of werkzeug: * https://pypi.python.org/simple/werkzeug/ Getting page https://pypi.python.org/simple/werkzeug/ Looking up "https://pypi.python.org/simple/werkzeug/" in the cache Current age based on date: 124 Freshness lifetime from max-age: 600 Freshness lifetime from request max-age: 600 The response is "fresh", returning cached response 600 > 124 Analyzing links from page https://pypi.python.org/simple/werkzeug/ Skipping link https://pypi.python.org/packages/0b/37/398042f9b852c57f7e9b4e1173dcd40e7b9980d9c76a700647c458f582b1/Werkzeug-0.11.1-py2.py3-none-any.whl#md5=ff8452a255afa44a5fcb1b79a3da2f27 (from https://pypi.python.org/simple/werkzeug/); No binaries permitted for werkzeug [...] Found link https://pypi.python.org/packages/fe/7f/6d70f765ce5484e07576313897793cb49333dd34e462488ee818d17244af/Werkzeug-0.11.15.tar.gz#md5=cb4010478dd33905f95920e4880204a2 (from https://pypi.python.org/simple/werkzeug/), version: 0.11.15 Using version 0.12.1 (newest of versions: 0.1, 0.2, 0.3, 0.3.1, 0.4, 0.4.1, 0.5, 0.5.1, 0.6, 0.6.1, 0.6.2, 0.7, 0.7.1, 0.7.2, 0.8, 0.8.1, 0.8.2, 0.8.3, 0.9, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.10, 0.10.1, 0.10.2, 0.10.4, 0.11, 0.11.1, 0.11.2, 0.11.3, 0.11.4, 0.11.5, 0.11.6, 0.11.7, 0.11.8, 0.11.9, 0.11.10, 0.11.11, 0.11.12, 0.11.13, 0.11.14, 0.11.15, 0.12, 0.12.1) Looking up "https://pypi.python.org/packages/ab/65/d3f1edd1109cb1beb6b82f4139addad482df5b5ea113bdc98242383bf402/Werkzeug-0.12.1.tar.gz" in the cache Current age based on date: 80370 Freshness lifetime from max-age: 31557600 The response is "fresh", returning cached response 31557600 > 80370 Using cached Werkzeug-0.12.1.tar.gz Downloading from URL https://pypi.python.org/packages/ab/65/d3f1edd1109cb1beb6b82f4139addad482df5b5ea113bdc98242383bf402/Werkzeug-0.12.1.tar.gz#md5=b1c7bbe0066c0578116d75fef65c7eb3 (from https://pypi.python.org/simple/werkzeug/) Running setup.py (path:/private/var/folders/5l/jc83jsrs0nl4vkk9qyv0n1f00000gn/T/pip-build-7r4v773m/werkzeug/setup.py) egg_info for package werkzeug Running command python setup.py egg_info running egg_info creating pip-egg-info/Werkzeug.egg-info writing pip-egg-info/Werkzeug.egg-info/PKG-INFO writing dependency_links to pip-egg-info/Werkzeug.egg-info/dependency_links.txt writing requirements to pip-egg-info/Werkzeug.egg-info/requires.txt writing top-level names to pip-egg-info/Werkzeug.egg-info/top_level.txt writing manifest file 'pip-egg-info/Werkzeug.egg-info/SOURCES.txt' reading manifest file 'pip-egg-info/Werkzeug.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_themes' warning: no previously-included files matching '*.py[cdo]' found anywhere in distribution warning: no previously-included files matching '__pycache__' found anywhere in distribution warning: no previously-included files matching '*.so' found anywhere in distribution warning: no previously-included files matching '*.pyd' found anywhere in distribution writing manifest file 'pip-egg-info/Werkzeug.egg-info/SOURCES.txt' Source in /private/var/folders/5l/jc83jsrs0nl4vkk9qyv0n1f00000gn/T/pip-build-7r4v773m/werkzeug has version 0.12.1, which satisfies requirement werkzeug from https://pypi.python.org/packages/ab/65/d3f1edd1109cb1beb6b82f4139addad482df5b5ea113bdc98242383bf402/Werkzeug-0.12.1.tar.gz#md5=b1c7bbe0066c0578116d75fef65c7eb3 Skipping bdist_wheel for werkzeug, due to binaries being disabled for it. Installing collected packages: werkzeug Running setup.py install for werkzeug ... Running command /usr/local/opt/python3/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/var/folders/5l/jc83jsrs0nl4vkk9qyv0n1f00000gn/T/pip-build-7r4v773m/werkzeug/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/5l/jc83jsrs0nl4vkk9qyv0n1f00000gn/T/pip-tmmuud28-record/install-record.txt --single-version-externally-managed --compile --prefix=nodepy_modules/.pip running install running build running build_py creating build creating build/lib creating build/lib/werkzeug copying werkzeug/__init__.py -> build/lib/werkzeug [...] running egg_info writing Werkzeug.egg-info/PKG-INFO writing dependency_links to Werkzeug.egg-info/dependency_links.txt writing requirements to Werkzeug.egg-info/requires.txt writing top-level names to Werkzeug.egg-info/top_level.txt reading manifest file 'Werkzeug.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_themes' warning: no previously-included files matching '*.py[cdo]' found anywhere in distribution warning: no previously-included files matching '__pycache__' found anywhere in distribution warning: no previously-included files matching '*.so' found anywhere in distribution warning: no previously-included files matching '*.pyd' found anywhere in distribution writing manifest file 'Werkzeug.egg-info/SOURCES.txt' creating build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/FONT_LICENSE -> build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/console.png -> build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/debugger.js -> build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/jquery.js -> build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/less.png -> build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/more.png -> build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/source.png -> build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/style.css -> build/lib/werkzeug/debug/shared copying werkzeug/debug/shared/ubuntu.ttf -> build/lib/werkzeug/debug/shared warning: build_py: byte-compiling is disabled, skipping. running install_lib creating nodepy_modules creating nodepy_modules/.pip creating nodepy_modules/.pip/lib creating nodepy_modules/.pip/lib/python3.6 creating nodepy_modules/.pip/lib/python3.6/site-packages creating nodepy_modules/.pip/lib/python3.6/site-packages/werkzeug copying build/lib/werkzeug/__init__.py -> nodepy_modules/.pip/lib/python3.6/site-packages/werkzeug [...] copying build/lib/werkzeug/useragents.py -> nodepy_modules/.pip/lib/python3.6/site-packages/werkzeug copying build/lib/werkzeug/utils.py -> nodepy_modules/.pip/lib/python3.6/site-packages/werkzeug copying build/lib/werkzeug/wrappers.py -> nodepy_modules/.pip/lib/python3.6/site-packages/werkzeug copying build/lib/werkzeug/wsgi.py -> nodepy_modules/.pip/lib/python3.6/site-packages/werkzeug warning: install_lib: byte-compiling is disabled, skipping. running install_egg_info Copying Werkzeug.egg-info to nodepy_modules/.pip/lib/python3.6/site-packages/Werkzeug-0.12.1-py3.6.egg-info running install_scripts writing list of installed files to '/var/folders/5l/jc83jsrs0nl4vkk9qyv0n1f00000gn/T/pip-tmmuud28-record/install-record.txt' done Cleaning up... Removing source in /private/var/folders/5l/jc83jsrs0nl4vkk9qyv0n1f00000gn/T/pip-build-7r4v773m/werkzeug Exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python3.6/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python3.6/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python3.6/site-packages/pip/req/req_install.py", line 922, in install with open(inst_files_path, 'w') as f: FileNotFoundError: [Errno 2] No such file or directory: 'nodepy_modules/.pip/lib/python3.6/site-packages/Werkzeug-0.12.1-py3.6.egg-info/installed-files.txt' ``` This is not limited to Werkzeug. It does not happen when I use `--user --install-option="--prefix="` instead, but of course that installs to the user location. Ths method of installation is related to Homebrew setting the `prefix` option, see https://github.com/Homebrew/brew/blob/master/docs/Homebrew-and-Python.md#note-on-pip-install---user . The solution mentioned in [this](http://stackoverflow.com/a/41143578/791713) StackOverflow answer, works. I wonder then, why `--install-option=--prefix=` does not have the exact same effect. *Edit* It breaks installations without `--user` or `--prefix` though. Found a command to reproduce this issue on Windows. Pip version is 9.0.1. Using the `--target` option instead makes it work, but that will only install libraries but no scripts, etc. ``` $ pip install --prefix nodepy_modules\.pip markdown==2.6.8 Flask-HTTPAuth==3.2.2 Pygments==2.2.0 Flask==0.12 mongoengine==0.11.0 mkdocs==0.16.1 Flask-RESTful==0.3.5 Requirement already satisfied: markdown==2.6.8 in c:\python35-32\lib\site-packages Requirement already satisfied: Flask-HTTPAuth==3.2.2 in c:\python35-32\lib\site-packages Collecting Pygments==2.2.0 Using cached Pygments-2.2.0-py2.py3-none-any.whl Requirement already satisfied: Flask==0.12 in c:\python35-32\lib\site-packages Requirement already satisfied: mongoengine==0.11.0 in c:\python35-32\lib\site-packages Collecting mkdocs==0.16.1 Using cached mkdocs-0.16.1-py2.py3-none-any.whl Collecting Flask-RESTful==0.3.5 Using cached Flask_RESTful-0.3.5-py2.py3-none-any.whl Requirement already satisfied: itsdangerous>=0.21 in c:\python35-32\lib\site-packages (from Flask==0.12) Requirement already satisfied: click>=2.0 in c:\python35-32\lib\site-packages (from Flask==0.12) Requirement already satisfied: Werkzeug>=0.7 in c:\python35-32\lib\site-packages (from Flask==0.12) Requirement already satisfied: Jinja2>=2.4 in c:\python35-32\lib\site-packages (from Flask==0.12) Requirement already satisfied: six in c:\python35-32\lib\site-packages (from mongoengine==0.11.0) Requirement already satisfied: pymongo>=2.7.1 in c:\python35-32\lib\site-packages (from mongoengine==0.11.0) Requirement already satisfied: PyYAML>=3.10 in c:\python35-32\lib\site-packages (from mkdocs==0.16.1) Requirement already satisfied: livereload>=2.3.2 in c:\python35-32\lib\site-packages (from mkdocs==0.16.1) Requirement already satisfied: tornado>=4.1 in c:\python35-32\lib\site-packages (from mkdocs==0.16.1) Requirement already satisfied: pytz in c:\python35-32\lib\site-packages (from Flask-RESTful==0.3.5) Collecting aniso8601>=0.82 (from Flask-RESTful==0.3.5) Using cached aniso8601-1.2.1.tar.gz Requirement already satisfied: MarkupSafe in c:\python35-32\lib\site-packages (from Jinja2>=2.4->Flask==0.12) Requirement already satisfied: python-dateutil in c:\python35-32\lib\site-packages (from aniso8601>=0.82->Flask-RESTful==0.3.5) Installing collected packages: Pygments, mkdocs, aniso8601, Flask-RESTful Running setup.py install for aniso8601 ... done Exception: Traceback (most recent call last): File "c:\python35-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\python35-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\python35-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\python35-32\lib\site-packages\pip\req\req_install.py", line 922, in install with open(inst_files_path, 'w') as f: FileNotFoundError: [Errno 2] No such file or directory: 'nodepy_modules.pip\\Lib\\site-packages\\aniso8601-1.2.1-py3.5.egg-info\\installed-files.txt' ```
2017-05-18T11:38:42Z
[]
[]
Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 126, in main self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 228, in run requirement_set.install(install_options, global_options) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1093, in install requirement.install(install_options, global_options) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 593, in install f = open(os.path.join(egg_info_dir, 'installed-files.txt'), 'w') IOError: [Errno 2] No such file or directory: '/usr/lib/python2.7/site-packages/tgMochiKit-1.4.2-py2.7.egg-info/installed-files.txt'
17,353
pypa/pip
pypa__pip-481
00a2234a38d20d67ecc4b352b934a73840f215e0
diff --git a/pip/vcs/__init__.py b/pip/vcs/__init__.py --- a/pip/vcs/__init__.py +++ b/pip/vcs/__init__.py @@ -115,6 +115,9 @@ def get_url_rev(self): Returns the correct repository URL and revision by parsing the given repository URL """ + error_message= "Sorry, '{}' is a malformed url. In requirements files, the \ +format is <vcs>+<protocol>://<url>, e.g. svn+http://myrepo/svn/MyApp#egg=MyApp" + assert '+' in self.url, error_message.format(self.url) url = self.url.split('+', 1)[1] scheme, netloc, path, query, frag = urlparse.urlsplit(url) rev = None
Bad error message on malformed VCS string The item in my requirements.txt: ``` git://github.com/alex/django-fixture-generator.git#egg=fixture_generator ``` The resulting error message: ``` python Downloading/unpacking fixture-generator from git://github.com/alex/django-fixture-generator.git (from -r requirements/development.txt (line 3)) Exception: Traceback (most recent call last): File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/basecommand.py", line 126, in main self.run(options, args) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/commands/install.py", line 223, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py", line 961, in prepare_files self.unpack_url(url, location, self.is_download) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py", line 1073, in unpack_url return unpack_vcs_link(link, location, only_download) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py", line 293, in unpack_vcs_link vcs_backend.unpack(location) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/__init__.py", line 225, in unpack self.obtain(location) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/git.py", line 97, in obtain url, rev = self.get_url_rev() File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/git.py", line 183, in get_url_rev url, rev = super(Git, self).get_url_rev() File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/__init__.py", line 117, in get_url_rev url = self.url.split('+', 1)[1] IndexError: list index out of range ```
Yeah we definitely should do better, probably should fix consistently across all vcs backends ensuring bare scheme is handled correctly.
2012-03-13T22:43:56Z
[]
[]
Traceback (most recent call last): File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/basecommand.py", line 126, in main self.run(options, args) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/commands/install.py", line 223, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py", line 961, in prepare_files self.unpack_url(url, location, self.is_download) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py", line 1073, in unpack_url return unpack_vcs_link(link, location, only_download) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/download.py", line 293, in unpack_vcs_link vcs_backend.unpack(location) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/__init__.py", line 225, in unpack self.obtain(location) File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/git.py", line 97, in obtain url, rev = self.get_url_rev() File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/git.py", line 183, in get_url_rev url, rev = super(Git, self).get_url_rev() File "/home/alex/.virtualenvs/tracebin/local/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/__init__.py", line 117, in get_url_rev url = self.url.split('+', 1)[1] IndexError: list index out of range
17,368
pypa/pip
pypa__pip-4976
2e7e1a972d534039c9ba607acfb739367cd0bb48
diff --git a/src/pip/_internal/baseparser.py b/src/pip/_internal/baseparser.py --- a/src/pip/_internal/baseparser.py +++ b/src/pip/_internal/baseparser.py @@ -9,7 +9,7 @@ from pip._vendor.six import string_types -from pip._internal.configuration import Configuration +from pip._internal.configuration import Configuration, ConfigurationError from pip._internal.utils.misc import get_terminal_size logger = logging.getLogger(__name__) @@ -177,9 +177,6 @@ def _update_defaults(self, defaults): the environ. Does a little special handling for certain types of options (lists).""" - # Load the configuration - self.config.load() - # Accumulate complex default state. self.values = optparse.Values(self.defaults) late_eval = set() @@ -224,6 +221,12 @@ def get_default_values(self): # Old, pre-Optik 1.5 behaviour. return optparse.Values(self.defaults) + # Load the configuration, or error out in case of an error + try: + self.config.load() + except ConfigurationError as err: + self.exit(2, err.args[0]) + defaults = self._update_defaults(self.defaults.copy()) # ours for option in self._get_all_options(): default = defaults.get(option.dest) diff --git a/src/pip/_internal/configuration.py b/src/pip/_internal/configuration.py --- a/src/pip/_internal/configuration.py +++ b/src/pip/_internal/configuration.py @@ -11,6 +11,7 @@ A single word describing where the configuration key-value pair came from """ +import locale import logging import os @@ -283,8 +284,14 @@ def _construct_parser(self, fname): # Doing this is useful when modifying and saving files, where we don't # need to construct a parser. if os.path.exists(fname): - parser.read(fname) - + try: + parser.read(fname) + except UnicodeDecodeError: + raise ConfigurationError(( + "ERROR: " + "Configuration file contains invalid %s characters.\n" + "Please fix your configuration, located at %s\n" + ) % (locale.getpreferredencoding(False), fname)) return parser def _load_environment_vars(self):
UnicodeDecodeError when using pip * Pip version: 10.0.0.dev0 * Python version: 3.5.4 * Operating system: windows 10, 1709, 64-bit ### Description: When i used `pip list` command in CMD, i got this error: `UnicodeDecodeError: 'gbk' codec can't decode byte 0x90 in position 101: illegal multibyte sequence`. Other pip command like `pip install xxx` gave me same error. I have tried following methods, but nothing changed. + try pip 9.0.1(after this failed, i tried pip 10.0.0 installed it from sorce code) + try `chcp 65001` + try python 3.6.4 + try robinxb's method from issue #4251, though the error occured were not quite the same. ### What I've run: ``` C:\Users\cyl>pip list Traceback (most recent call last): File "C:\Users\cyl\AppData\Local\Programs\Python\Python35\Scripts\pip-script.py", line 11, in <module> load_entry_point('pip==10.0.0.dev0', 'console_scripts', 'pip')() File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\__init__.py", line 229, in main cmd_name, cmd_args = parseopts(args) File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\__init__.py", line 178, in parseopts general_options, args_else = parser.parse_args(args) File "C:\Users\cyl\AppData\Local\Programs\Python\Python35\lib\optparse.py", line 1370, in parse_args values = self.get_default_values() File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\baseparser.py", line 227, in get_default_values defaults = self._update_defaults(self.defaults.copy()) # ours File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\baseparser.py", line 181, in _update_defaults self.config.load() File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\configuration.py", line 111, in load self._load_config_files() File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\configuration.py", line 262, in _load_config_files parser = self._load_file(variant, fname) File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\configuration.py", line 270, in _load_file parser = self._construct_parser(fname) File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\configuration.py", line 286, in _construct_parser parser.read(fname) File "C:\Users\cyl\AppData\Local\Programs\Python\Python35\lib\configparser.py", line 696, in read self._read(fp, filename) File "C:\Users\cyl\AppData\Local\Programs\Python\Python35\lib\configparser.py", line 1012, in _read for lineno, line in enumerate(fp, start=1): UnicodeDecodeError: 'gbk' codec can't decode byte 0x90 in position 101: illegal multibyte sequence ```
Hi @TDilcy! This is because of an encoding releated error while reading pip's configuration file. Could you look in the pip configuration file to check and see if there's a stray character there that might be causing this crash? It should be `%APPDATA%\pip\pip.ini`. None the less, pip should probably print a better error message in this case. :) Specifically, your `pip.ini` file should contain text in your PC's default (ANSI) encoding. Using `chcp` won't affect that, as that only alters the *console* codepage, not the ANSI one. As you noticed, #4251 is a different issue, and the fix for that (which is in pip 10.0.0dev0) doesn't affect this problem. (Prior to Python 3.2, the encoding support in `ConfigParser` was very limited, so we'll have problems improving the current behaviour until we can drop Python 2.x support :cry: ) Just to confirm... @pfmoore just printing a message saying "hey, I couldn't read this configuration file because of this error" which prints the traceback on verbose, would be an acceptable improvement for now; correct? Yeah, that's a fair point :-) You could even note the expected encoding by checking `locale.getpreferredencoding(False)`. > You could even note the expected encoding by checking locale.getpreferredencoding(False). Sounds good. :) Uhm... So I forgot that configuration is loaded _before_ command line arguments are parsed. So, we can't really have it conditional on verbosity. Printing the entire traceback every single time is not a really the best thing we can do but that's the only idea I have right now; thoughts? If we're catching precisely that error in precisely that line of code, i don't see that we need the traceback. Just give a helpful error message, terminate the program, and you're done. ``` > pip list ERROR: Configuration file contains invalid cp1252 characters. Please fix your config (located at C:\Users\XXXX\AppData\Roaming\Pip\pip.ini) ``` @pfmoore thanks, but i have reinstalled my windows 10 to solve the problem...... :joy:
2018-01-20T04:54:13Z
[]
[]
Traceback (most recent call last): File "C:\Users\cyl\AppData\Local\Programs\Python\Python35\Scripts\pip-script.py", line 11, in <module> load_entry_point('pip==10.0.0.dev0', 'console_scripts', 'pip')() File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\__init__.py", line 229, in main cmd_name, cmd_args = parseopts(args) File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\__init__.py", line 178, in parseopts general_options, args_else = parser.parse_args(args) File "C:\Users\cyl\AppData\Local\Programs\Python\Python35\lib\optparse.py", line 1370, in parse_args values = self.get_default_values() File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\baseparser.py", line 227, in get_default_values defaults = self._update_defaults(self.defaults.copy()) # ours File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\baseparser.py", line 181, in _update_defaults self.config.load() File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\configuration.py", line 111, in load self._load_config_files() File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\configuration.py", line 262, in _load_config_files parser = self._load_file(variant, fname) File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\configuration.py", line 270, in _load_file parser = self._construct_parser(fname) File "c:\users\cyl\appdata\local\programs\python\python35\lib\site-packages\pip-10.0.0.dev0-py3.5.egg\pip\_internal\configuration.py", line 286, in _construct_parser parser.read(fname) File "C:\Users\cyl\AppData\Local\Programs\Python\Python35\lib\configparser.py", line 696, in read self._read(fp, filename) File "C:\Users\cyl\AppData\Local\Programs\Python\Python35\lib\configparser.py", line 1012, in _read for lineno, line in enumerate(fp, start=1): UnicodeDecodeError: 'gbk' codec can't decode byte 0x90 in position 101: illegal multibyte sequence
17,375
pypa/pip
pypa__pip-5055
9f942d00fcd18e87cffc180a128723f169699a1e
diff --git a/src/pip/_internal/cmdoptions.py b/src/pip/_internal/cmdoptions.py --- a/src/pip/_internal/cmdoptions.py +++ b/src/pip/_internal/cmdoptions.py @@ -440,7 +440,8 @@ def only_binary(): help='Directory to unpack packages into and build in. Note that ' 'an initial build still takes place in a temporary directory. ' 'The location of temporary directories can be controlled by setting ' - 'the TMPDIR environment variable (TEMP on Windows) appropriately.' + 'the TMPDIR environment variable (TEMP on Windows) appropriately. ' + 'When passed, build directories are not cleaned in case of failures.' ) # type: Any ignore_requires_python = partial(
pip install pgraph - AssertionError: Multiple .dist-info directories - Pip version: 8.1.0 - Python version: 2.7.11+ - Operating System: Linux lab 4.3.0-kali1-686-pae ### Description: Please try to install **pgraph** with command: `sudo pip install pgraph --upgrade`, ### What I've run: ``` root@lab:~/# uname -a Linux lab 4.3.0-kali1-686-pae #1 SMP Debian 4.3.5-1kali1 (2016-02-11) i686 GNU/Linux root@lab:~/# pip install pgraph --upgrade Collecting pgraph Requirement already up-to-date: pyramid-chameleon in /usr/local/lib/python2.7/dist-packages (from pgraph) Requirement already up-to-date: pyramid in /usr/local/lib/python2.7/dist-packages (from pgraph) Requirement already up-to-date: webtest in /usr/local/lib/python2.7/dist-packages (from pgraph) Requirement already up-to-date: waitress in /usr/local/lib/python2.7/dist-packages (from pgraph) Requirement already up-to-date: mock in /usr/local/lib/python2.7/dist-packages (from pgraph) Collecting py-deps[memcache]>=0.5.5 (from pgraph) Requirement already up-to-date: celery in /usr/local/lib/python2.7/dist-packages (from pgraph) Requirement already up-to-date: pyramid-debugtoolbar in /usr/local/lib/python2.7/dist-packages (from pgraph) Requirement already up-to-date: funcsigs in /usr/local/lib/python2.7/dist-packages (from pgraph) Requirement already up-to-date: Chameleon in /usr/local/lib/python2.7/dist-packages (from pyramid-chameleon->pgraph) Requirement already up-to-date: setuptools in /usr/local/lib/python2.7/dist-packages (from pyramid->pgraph) Requirement already up-to-date: repoze.lru>=0.4 in /usr/local/lib/python2.7/dist-packages (from pyramid->pgraph) Requirement already up-to-date: zope.interface>=3.8.0 in /usr/lib/python2.7/dist-packages (from pyramid->pgraph) Requirement already up-to-date: PasteDeploy>=1.5.0 in /usr/local/lib/python2.7/dist-packages (from pyramid->pgraph) Requirement already up-to-date: WebOb>=1.3.1 in /usr/local/lib/python2.7/dist-packages (from pyramid->pgraph) Requirement already up-to-date: translationstring>=0.4 in /usr/local/lib/python2.7/dist-packages (from pyramid->pgraph) Requirement already up-to-date: zope.deprecation>=3.5.0 in /usr/local/lib/python2.7/dist-packages (from pyramid->pgraph) Requirement already up-to-date: venusian>=1.0a3 in /usr/local/lib/python2.7/dist-packages (from pyramid->pgraph) Requirement already up-to-date: six in /usr/lib/python2.7/dist-packages (from webtest->pgraph) Requirement already up-to-date: beautifulsoup4 in /usr/lib/python2.7/dist-packages (from webtest->pgraph) Requirement already up-to-date: pbr>=0.11 in /usr/local/lib/python2.7/dist-packages (from mock->pgraph) Requirement already up-to-date: networkx in /usr/local/lib/python2.7/dist-packages (from py-deps[memcache]>=0.5.5->pgraph) Requirement already up-to-date: wheel in /usr/local/lib/python2.7/dist-packages (from py-deps[memcache]>=0.5.5->pgraph) Requirement already up-to-date: pip>=6.0.1 in /usr/local/lib/python2.7/dist-packages (from py-deps[memcache]>=0.5.5->pgraph) Requirement already up-to-date: pylibmc in /usr/local/lib/python2.7/dist-packages (from py-deps[memcache]>=0.5.5->pgraph) Requirement already up-to-date: kombu<3.1,>=3.0.34 in /usr/local/lib/python2.7/dist-packages (from celery->pgraph) Requirement already up-to-date: pytz>dev in /usr/lib/python2.7/dist-packages (from celery->pgraph) Requirement already up-to-date: billiard<3.4,>=3.3.0.23 in /usr/local/lib/python2.7/dist-packages (from celery->pgraph) Requirement already up-to-date: pyramid-mako>=0.3.1 in /usr/local/lib/python2.7/dist-packages (from pyramid-debugtoolbar->pgraph) Collecting Pygments (from pyramid-debugtoolbar->pgraph) Using cached Pygments-2.1.3-py2.py3-none-any.whl Collecting decorator>=3.4.0 (from networkx->py-deps[memcache]>=0.5.5->pgraph) Using cached decorator-4.0.9-py2.py3-none-any.whl Requirement already up-to-date: anyjson>=0.3.3 in /usr/local/lib/python2.7/dist-packages (from kombu<3.1,>=3.0.34->celery->pgraph) Requirement already up-to-date: amqp<2.0,>=1.4.9 in /usr/local/lib/python2.7/dist-packages (from kombu<3.1,>=3.0.34->celery->pgraph) Collecting Mako>=0.8 (from pyramid-mako>=0.3.1->pyramid-debugtoolbar->pgraph) Requirement already up-to-date: MarkupSafe>=0.9.2 in /usr/lib/python2.7/dist-packages (from Mako>=0.8->pyramid-mako>=0.3.1->pyramid-debugtoolbar->pgraph) Installing collected packages: py-deps, pgraph, Pygments, decorator, Mako Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 732, in install **kwargs File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 835, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 1030, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 344, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 304, in clobber assert not info_dir, 'Multiple .dist-info directories' AssertionError: Multiple .dist-info directories ```
As described in issue #1964, the error message needs to be corrected: > The error is very confusing and doesn't include any hint on which is the real problem, which are the "multiple" ones, these are not listed even in the pip.log Please correct the error message, to give the necessary information for the user to know what to do to address the problem. Closing this, I believe this is an issue with the specific package file on PyPI and is not a pip issue. This continues to happen for me, on different code bases. An example from today: ``` $ python3 -m pip install . Processing /home/bignose/Projects/maildrake/trunk Collecting docutils (from maildrake===NEXT) Using cached docutils-0.13.1-py3-none-any.whl Collecting fasteners (from maildrake===NEXT) Using cached fasteners-0.14.1-py2.py3-none-any.whl Collecting setuptools (from maildrake===NEXT) Using cached setuptools-34.3.2-py2.py3-none-any.whl Collecting sqlparse (from maildrake===NEXT) Using cached sqlparse-0.2.3-py2.py3-none-any.whl Collecting monotonic>=0.1 (from fasteners->maildrake===NEXT) Using cached monotonic-1.3-py2.py3-none-any.whl Collecting six (from fasteners->maildrake===NEXT) Using cached six-1.10.0-py2.py3-none-any.whl Collecting packaging>=16.8 (from setuptools->maildrake===NEXT) Using cached packaging-16.8-py2.py3-none-any.whl Collecting appdirs>=1.4.0 (from setuptools->maildrake===NEXT) Using cached appdirs-1.4.3-py2.py3-none-any.whl Collecting pyparsing (from packaging>=16.8->setuptools->maildrake===NEXT) Using cached pyparsing-2.2.0-py2.py3-none-any.whl Installing collected packages: docutils, monotonic, six, fasteners, pyparsing, packaging, appdirs, setuptools, sqlparse, maildrake Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 360, in run prefix=options.prefix_path, File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/lib/python3/dist-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python3/dist-packages/pip/wheel.py", line 305, in clobber ', '.join(info_dir)) AssertionError: Multiple .dist-info directories: /home/bignose/.local/lib/python3.5/site-packages/monotonic-1.2.dist-info, /home/bignose/.local/lib/python3.5/site-packages/monotonic-1.3.dist-info $ ls /home/bignose/.local/lib/python3.5/site-packages/monotonic-* ls: cannot access '/home/bignose/.local/lib/python3.5/site-packages/monotonic-*': No such file or directory ``` So, for some reason the “Multiple .dist-info directories” message reports two files that *both don't exist* after the command exits. This makes it difficult to know what even went wrong. This continues to happen even in a clean virtualenv, and when I explicitly clear the Pip cache: ``` (temp_venv) $ rm -r ~/.cache/pip/* (temp_venv) $ python3 -m pip install ../trunk/dist/maildrake-0.1.2-py2.py3-none-any.whl Processing /home/bignose/Projects/maildrake/trunk/dist/maildrake-0.1.2-py2.py3-none-any.whl Requirement already satisfied: semver in ./lib/python3.5/site-packages (from maildrake==0.1.2) Requirement already satisfied: docutils in ./lib/python3.5/site-packages (from maildrake==0.1.2) Requirement already satisfied: setuptools in ./lib/python3.5/site-packages (from maildrake==0.1.2) Collecting fasteners (from maildrake==0.1.2) Downloading fasteners-0.14.1-py2.py3-none-any.whl Requirement already satisfied: sqlparse in ./lib/python3.5/site-packages (from maildrake==0.1.2) Collecting monotonic>=0.1 (from fasteners->maildrake==0.1.2) Downloading monotonic-1.3-py2.py3-none-any.whl Collecting six (from fasteners->maildrake==0.1.2) Downloading six-1.10.0-py2.py3-none-any.whl Installing collected packages: monotonic, six, fasteners, maildrake Exception: Traceback (most recent call last): File "/home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/pip/commands/install.py", line 360, in run prefix=options.prefix_path, File "/home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/pip/wheel.py", line 305, in clobber ', '.join(info_dir)) AssertionError: Multiple .dist-info directories: /home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/monotonic-1.2.dist-info, /home/bignose/Projects/maildrake/temp_venv/lib/python3.5/site-packages/monotonic-1.3.dist-info ``` There is no information given to help trace where these “multiple .dist-info directories” are coming from, what's making them appear, and what can be done to stop them from appearing. How can this be diagnosed further? @bignose-debian Can you publish ``maildrake-0.1.2-py2.py3-none-any.whl`` somewhere? ping, we would need the aforementioned wheel. I suspect two `.dist-info` in the wheel, just like in #1964 I managed to resolve this, temporarily. I deleted files from inside the cache for Pip. `$ rm /var/local/cache/pip/*` The cache is in a directory that is completely different from any of the filenames in the error message, so it's not at all clear whether or why this would change the behaviour. My Pip configuration is: ``` $ cat ~/.pip/pip.conf # $HOME/.pip/pip.conf # User-specific configuration for PIP installer for Python packages. [global] download-cache = /var/local/cache/pip [install] build-directory = /var/local/devel/bignose/virtualenvs/build source-directory = /var/local/devel/bignose/virtualenvs/src ``` Ah, that means a broken wheel got cached at one point and then kept getting reused. > […] a broken wheel got cached at one point and then kept getting reused. So, from my position the bug here is that Pip is giving a message that is totally unhelpful for diagnosing that problem. What should it say, instead, that would allow the reader to immediately know that (and not something else) is the problem? > […] a broken wheel got cached at one point and then kept getting reused. So, how can I prevent this from happening? I am in the position of needing to frequently delete all files under the configured ‘build-directory’ in order to avoid the unhelpful error message here. While #1964 was closed and we now have a better error, I think that this is still a bug. I have double checked and the wheels have a single .dist-info folder. I also got the same issue for tar.gz files This is triggered only when I am using a custom 'build' folder. The build folder does contain multiple .dist-info, one for the existing version, and one for the version which is going to be installed. For my project I am pinning everything, so when switching between branches it is common for the CI to reinstall older versions. An easy way to reproduce it ``` $ virtualenv pip-build-3564 $ cd pip-build-3564/ $ . bin/activate $ mkdir build $ pip install -b build bunch==1.0.0 # All good $ pip install -b build bunch==1.0.1 AssertionError: Multiple .dist-info directories: /home/adi/tmp/pip-build-3564/lib/python2.7/site-packages/bunch-1.0.0.dist-info, /home/adi/tmp/pip-build-3564/lib/python2.7/site-packages/bunch-1.0.1.dist-info ``` I have standard Ubuntu 16.04-x64 ``` $ python --version Python 2.7.12 $ pip --version pip 9.0.1 ``` If I remove the build folder, all is fine. Thanks! Hmm, that sounds like a simple case of you not cleaning up the build directory before doing a rebuild (I guess the point here is to allow incremental builds?). I don't really have much experience with the ```-b``` option and the reasons why people might need it, so I can't say if that's something you'd expect people to do. @pypa/pip-committers any thoughts? I am using a custom build folder so that the CI runs in as much isolation as possible. I am not using Travis, but buildbot, so the build system is not erased between builds.... and the same build system is running multiple tests in parallel, (for multiple projects), each in its won virtualenv --------- It might be the case that the build folder needs a manual build. I noted that there is the `--no-clean` argument. I am not using it, so I was assuming that pip will automatically clean. -------- Note that for the above example, those are the actual steps that I am running...but a simple upgrading of the package > Hmm, that sounds like a simple case of you not cleaning up the build directory before doing a rebuild The ‘pip’ configuration setting, ‘build-directory’, specifies the build directory for Pip. Are you saying that Pip will crash if that directory is not *manually* cleaned, between ‘pip install’ invocations? If so, it seems you're describing what needs to be corrected in Pip's behaviour to resolve this bug. See https://github.com/pypa/pip/issues/3564#issuecomment-297950139 It contains a set of commands which executed will trigger the failure. You can try to run them on your system. But yes. Pip fails if the directory is not manually cleaned.... but only when using a "custom" build folder with `pip install -b some/custom/path/which/needs/manual/clean SOME-PACKAGE` @bignose-debian I'm more suggesting that reusing pip's build directory is a bit more complex than supplying an empty directory to ```--build-directory```. Sure, pip could clean the build directory before use. But that would prevent any sort of incremental build optimisations - which is what some people use ```--build-directory``` for, I believe. But *not* cleaning out the build directory means that pip needs to be prepared for any sort of unexpected content in there (which as this issue shows, isn't always easy). I don't think there's a simple solution. At the moment, the rules are (roughly): 1. Without ```--build-directory```, pip will use a newly created empty directory for the build. 2. If the user specifies an empty directory in ```--build-directory```, pip will produce the same results as in (1), but will leave the output of the build process in the specified directory. 3. If the ```--build-directory``` is not empty, it's possible for pip to fail because there's unexpected content in there. It's the user's responsibility to resolve this issue. The problem here is (3). There may be room for some heuristics to improve the situation - for example, pip will delete any subdirectories named ```*.dist-info``` from the build directory before starting. But those heuristics may not always be right (an unlikely case, but consider an incremental build system where it's the building of the dist-info file that's complex). And there will always be the possibility of error (imagine if the build directory contained a write-protected file called ```setup.py```). And documenting precisely what pip will do to the supplied build directory (in a way that people will notice *before* pip corrupts something they want to keep!) will be important. I'm sure that PRs which improve things in case (3) will be of interest. I expect they'll cause a certain amount of debate, though, it's not obvious how (or even if) we should change things. Thanks @pfmoore for the explanation. But if pip install is not expected to clean the build directory, then why do we have this option: ``` --no-clean Don't clean up build directories. ``` I have never used incremental builds, but my expectation is that for incremental build you will use `--build-directory` together with `--no-clean` When the `--no-clean` flag is omitted, based on the current documentation I am expecting that the build directory to be cleaned. I am triggering this error with a happy path. The initial pip command is successfully executed and I am not passing the `--no-clean` flag... but the next call will fail ``` $ pip install -b build bunch==1.0.0 # All good $ pip install -b build bunch==1.0.1 AssertionError: Multiple .dist-info directories: /home/adi/tmp/pip-build-3564/lib/python2.7/site-packages/bunch-1.0.0.dist-info, /home/adi/tmp/pip-build-3564/lib/python2.7/site-packages/bunch-1.0.1.dist-info ``` @adiroiban Honestly, I don't know. There's a lot of historical stuff that's around this area that I wasn't involved in. My explanation may not be completely accurate - it's possible I've misunderstood stuff. Maybe there is a bug in that ```--build-directory``` should result in the build dir being emptied if ```--no-clean``` isn't specified. I don't know if the docs say anything specific here? @pfmoore don't worry. Your feedback is much appreciated. So for now, I don't see any difference between using install with or without `--no-clean` I have never used that incremental build thing... so I have no idea what is that :) So, in order to get a PR rolling it would help to get some feedback regarding the behavior for the `--no-clean` flag 1.pip install, custom build directory, without `--no-clean` ----------------------------------------------------------------------- ``` $ ls ./build-here ls: cannot access './build-here': No such file or directory $ pip install -b ./build-here bunch==1.0.0 $ ls ./build-here ls: cannot access './build-here': No such file or directory ``` This is what I am expecting to get... but for now I get the same results as for test case 2. That is, the build directory is not cleaned. 2.pip install, custom build directory, with `--no-clean` --------------------------------------------------------------------- ``` $ ls ./build-here ls: cannot access './build-here': No such file or directory $ pip install -b ./build-here --no-clean bunch==1.0.0 $ ls ./build-here/ bunch pip-delete-this-directory.txt ``` this is what I get now ... and based on the current documentation is what I am expecting The current expectation is that if you're specifying ``--build-directory`` then you're managing the lifecycle of that directory, not pip. @dstufft then the current implemenation is valid... maybe only not well documented.... and a bit awkward in relational tot the `--no-clean` flag Please note that I am talking about the `pip install` ` -b, --build <dir> ` option... as from ``` Install Options: -b, --build <dir> Directory to unpack packages into and build in. --no-clean Don't clean up build directories. ``` Not sure what `--build-directory` is. So, maybe the fix for this would be to extend the documentation to ``` -b, --build <dir> Directory to unpack packages into and build in. When in used, pip will not do any cleaning, even when --no-clean is NOT passed. You will have to do your own cleaning of this folder. --no-clean Don't clean up build directories. Build directory is never cleaned when a custom build directory is used. ``` @dstufft What do you say, does my comment make sense? Thanks! Documenting the current behavior better is always a +1 in my book. To be clear, I'm not dead set on maintaining that property, that is just the current expectation, a compelling argument *could* see it changed. One note though is that pip uses randomized build directories by default, so you shouldn't need to use ``--build`` at all to get isolated installs. There's also https://github.com/pypa/pip/issues/4371. > The current expectation is that if you're specifying --build-directory then you're managing the lifecycle of that directory, not pip. > […] that is just the current expectation, a compelling argument could see it changed. A build can sometimes crash; then the build directory is left in place, and nothing cleans it up. I set the ‘build-directory’ option in Pip's configuration file, so that when a build crashes the cruft isn't littering my virtualenv directory. So I do expect that Pip will at least not complain when the build directory is not empty; that it will gracefully handle the presence of previous build artefacts in that directory. > I set the ‘build-directory’ option in Pip's configuration file, so that when a build crashes the cruft isn't littering my virtualenv directory. pip uses a build directory located in ``TMPDIR`` by default, if the build crashes and leaves something behind presumably at some point the system will reclaim space by deleting temporary files.
2018-03-04T19:04:36Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 732, in install **kwargs File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 835, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 1030, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 344, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 304, in clobber assert not info_dir, 'Multiple .dist-info directories' AssertionError: Multiple .dist-info directories
17,380
pypa/pip
pypa__pip-5280
3e713708088aedb1cde32f3c94333d6e29aaf86e
diff --git a/src/pip/_internal/wheel.py b/src/pip/_internal/wheel.py --- a/src/pip/_internal/wheel.py +++ b/src/pip/_internal/wheel.py @@ -717,11 +717,11 @@ def build(self, requirements, session, autobuilding=False): ) elif autobuilding and req.editable: pass + elif autobuilding and not req.source_dir: + pass elif autobuilding and req.link and not req.link.is_artifact: # VCS checkout. Build wheel just for this run. buildset.append((req, True)) - elif autobuilding and not req.source_dir: - pass else: ephem_cache = False if autobuilding:
pip 10 is unable to install from non-editable VCS URLs * Pip version: 10.0.0 * Python version: 3.5.4 * Operating system: Linux ### Description: I'm trying to install a package from Git. ### What I've run: ```bash $ pip3 install git+ssh://git@example.com/mypackage.git#egg=mypackage ``` ``` Building wheels for collected packages: mypackage Exception: Traceback (most recent call last): File "/home/p/local/lib/python3.5/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/home/p/local/lib/python3.5/site-packages/pip/_internal/commands/install.py", line 305, in run session=session, autobuilding=True File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 773, in build python_tag=python_tag, File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 633, in _build_one python_tag=python_tag) File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 637, in _build_one_inside_env if self.__build_one(req, temp_dir.path, python_tag=python_tag): File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 663, in __build_one base_args = self._base_setup_args(req) File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 659, in _base_setup_args SETUPTOOLS_SHIM % req.setup_py File "/home/p/local/lib/python3.5/site-packages/pip/_internal/req/req_install.py", line 416, in setup_py assert self.source_dir, "No source dir for %s" % self AssertionError: No source dir for mypackage from git+ssh://git@example.com/mypackage.git#egg=mypackage in /home/p/local/lib/python3.5/site-packages ``` If I uninstall the package and then install, it works. But it continues to fail when trying install again.
I saw this same error on Python 2 and found that using pip 9 worked as expected. I wonder if this is related to the deprecation and removal of the egg switch? Removing that also seemed to solve the issue. I'm experiencing this issue on Travis-CI with Python 3.5.2 and ``pip==10.0.0``. ~~I do not experience it with Python 3.6 (local) or 2.7 (both local and on travis).~~ ```pytb Traceback (most recent call last): ... File "/home/travis/virtualenv/python3.5.2/lib/python3.5/site-packages/pip/_internal/req/req_install.py", line 415, in setup_py assert self.source_dir, "No source dir for %s" % self AssertionError: No source dir for cnx-query-grammar from git+https://github.com/Connexions/cnx-query-grammar.git#egg=cnx-query-grammar in /home/travis/virtualenv/python3.5.2/lib/python3.5/site-packages (from -r requirements/./test.txt (line 9)) ``` Exact same issue, on `Ubuntu 14.04.2 LTS`, pip 10.0.0 installed with get-pip.py on python 3.4.0 specifically on my git installs. Also using the #egg= parameter. I found this thread: https://github.com/pypa/pip/issues/1749 Oddly removing the whole virtualenv and reinstalling (including the get-pip bit) worked. ... but it failed again on the second deploy on top of an existing virtualenv (which should have been a no-op since all the packages are installed already but I guess it redownloads the git packages each time). Initial installation works, but attempts to reinstall are the problem space. So far I'm seeing a difference in the ``InstallRequirement``'s ``build_env`` value, where the initial install produced a `NoOpBuildEnvironment` object and a reinstall has a `BuildEnvironment`. Also experiencing this issue with pip 10.0.0 This breaks our ops/build workflows. 😢 In case others are also debugging this. I've narrowed down the two paths, first install and reinstall, to the difference in the results coming out of the [resolver's ``_get_abstract_dist_for``](https://github.com/pypa/pip/blob/master/src/pip/_internal/resolve.py#L257). Prior to that call both paths have ``<InstallRequirement>.source_dir == None``. After this call, only the first install path has a ``source_dir`` set to something other than ``None``. I'm guessing this is because it needs to go off and fetch the source during the first-install, but not on the reinstall. ... I could be off in the weeds though. It is my first time looking at this code. 😕 My workaround: `pip install pip==9.0.3` O... so the requirements file I'm working on isn't using `-e` prefixes for vcs installs. Adding `-e` to the beginning of the line does make this work. And in @RazerM 's case: ``pip3 install -e git+ssh://git@example.com/mypackage.git#egg=mypackage`` So part of this issue is user error??? The other part of it is that we should get back something to the effect of ``Requirement already satisfied: ...`` and instead we get a Traceback. If it helps, mine also doesn't use `-e`, though I thought VCS package URLs needn't be editable. [Correct, they needn't be:](https://pip.pypa.io/en/stable/reference/pip_install/#vcs-support) > VCS projects can be installed in editable mode (using the `--editable` option) or not. > > * For editable installs, the clone location by default is "\<venv path>/src/SomeProject" in virtual environments, and "\<cwd>/src/SomeProject" for global installs. The `--src` option can be used to modify this location. > * For non-editable installs, the project is built locally in a temp dir and then normally. Note that if a satisfactory version of the package is already installed, the VCS source will not overwrite it without an `--upgrade` flag. VCS requirements pin the package version (specified in the `setup.py` file) of the target commit, not necessarily the commit itself. > * The `pip freeze` subcommand will record the VCS requirement specifier (referencing a specific commit) if and only if the install is done using the editable option. FYI we are running into this in pipenv (our testing infrastructure caught this), here's what I can say on the topic: * This only impacts non-editable VCS installs (i.e. not passing `-e` * We explicitly pass a `PIP_SRC_DIR` during testing and it seems to make no difference * All of our tests run in isolated environments As far as the distinction between editable and non-editable dependencies, from a resolution standpoint we can resolve dependency graphs for editable dependencies but can't for non-editable dependencies. Still-- we test to ensure that they can be installed, which now fails. As a temporary fix we are moving our `pip install` calls to `python -m <vendored pip9> install` for compatibility. I am unable to reproduce this. Could someone provide steps to reproduce? If it's with in a docker container, that'd be awesome. Just run this twice with pip 10 in a clean venv, it will fail on the second try: pip install git+https://github.com/requests/requests.git#egg=requests I can't reproduce: ``` /tmp $ python -m venv env /tmp $ source env/bin/activate (env) /tmp $ pip install -U pip Collecting pip Downloading https://files.pythonhosted.org/packages/62/a1/0d452b6901b0157a0134fd27ba89bf95a857fbda64ba52e1ca2cf61d8412/pip-10.0.0-py2.py3-none-any.whl (1.3MB) 100% |████████████████████████████████| 1.3MB 854kB/s Installing collected packages: pip Found existing installation: pip 9.0.1 Uninstalling pip-9.0.1: Successfully uninstalled pip-9.0.1 Successfully installed pip-10.0.0 (env) /tmp $ pip install git+https://github.com/requests/requests.git#egg=requests Collecting requests from git+https://github.com/requests/requests.git#egg=requests Cloning https://github.com/requests/requests.git to /private/var/folders/px/dlfyqxyx3mx0t_yx3dvbb9nc0000gn/T/pip-install-32abmlma/requests Collecting chardet<3.1.0,>=3.0.2 (from requests) Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB) 100% |████████████████████████████████| 143kB 6.9MB/s Collecting idna<2.7,>=2.5 (from requests) Downloading https://files.pythonhosted.org/packages/27/cc/6dd9a3869f15c2edfab863b992838277279ce92663d334df9ecf5106f5c6/idna-2.6-py2.py3-none-any.whl (56kB) 100% |████████████████████████████████| 61kB 9.3MB/s Collecting urllib3<1.23,>=1.21.1 (from requests) Downloading https://files.pythonhosted.org/packages/63/cb/6965947c13a94236f6d4b8223e21beb4d576dc72e8130bd7880f600839b8/urllib3-1.22-py2.py3-none-any.whl (132kB) 100% |████████████████████████████████| 133kB 10.9MB/s Collecting certifi>=2017.4.17 (from requests) Downloading https://files.pythonhosted.org/packages/7c/e6/92ad559b7192d846975fc916b65f667c7b8c3a32bea7372340bfe9a15fa5/certifi-2018.4.16-py2.py3-none-any.whl (150kB) 100% |████████████████████████████████| 153kB 10.3MB/s Installing collected packages: chardet, idna, urllib3, certifi, requests Running setup.py install for requests ... done Successfully installed certifi-2018.4.16 chardet-3.0.4 idna-2.6 requests-2.18.4 urllib3-1.22 (env) /tmp $ pip install git+https://github.com/requests/requests.git#egg=requests Requirement already satisfied: requests from git+https://github.com/requests/requests.git#egg=requests in ./env/lib/python3.6/site-packages (2.18.4) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in ./env/lib/python3.6/site-packages (from requests) (3.0.4) Requirement already satisfied: idna<2.7,>=2.5 in ./env/lib/python3.6/site-packages (from requests) (2.6) Requirement already satisfied: urllib3<1.23,>=1.21.1 in ./env/lib/python3.6/site-packages (from requests) (1.22) Requirement already satisfied: certifi>=2017.4.17 in ./env/lib/python3.6/site-packages (from requests) (2018.4.16) ``` @di @pradyunsg first spotted: https://travis-ci.org/pypa/pipenv/jobs/367322542#L715 log: ```console ◰³ tempenv-3321664538cc  ~/g/pypa-pipenv   tmp $…  pip install --no-cache-dir pip Requirement already satisfied: pip in /home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages (10.0.0) ◰³ tempenv-3321664538cc  ~/g/pypa-pipenv   tmp $…  pip install git+https://github.com/benjaminp/six.git#egg=six Collecting six from git+https://github.com/benjaminp/six.git#egg=six Cloning https://github.com/benjaminp/six.git to /tmp/pip-install-2ff500pr/six Building wheels for collected packages: six Running setup.py bdist_wheel for six ... done Stored in directory: /tmp/pip-ephem-wheel-cache-ebgi9ij6/wheels/a9/36/0a/8173089e25b3c1df51c0bb21d21ec8dc5d7ee9d0ec9b6b51e1 Successfully built six Installing collected packages: six Successfully installed six-1.11.0 ◰³ tempenv-3321664538cc  ~/g/pypa-pipenv   tmp $…  pip install git+https://github.com/benjaminp/six.git#egg=six Requirement already satisfied: six from git+https://github.com/benjaminp/six.git#egg=six in /home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages (1.11.0) Building wheels for collected packages: six Exception: Traceback (most recent call last): File "/home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 305, in run session=session, autobuilding=True File "/home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages/pip/_internal/wheel.py", line 773, in build python_tag=python_tag, File "/home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages/pip/_internal/wheel.py", line 633, in _build_one python_tag=python_tag) File "/home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages/pip/_internal/wheel.py", line 637, in _build_one_inside_env if self.__build_one(req, temp_dir.path, python_tag=python_tag): File "/home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages/pip/_internal/wheel.py", line 663, in __build_one base_args = self._base_setup_args(req) File "/home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages/pip/_internal/wheel.py", line 659, in _base_setup_args SETUPTOOLS_SHIM % req.setup_py File "/home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages/pip/_internal/req/req_install.py", line 415, in setup_py assert self.source_dir, "No source dir for %s" % self AssertionError: No source dir for six from git+https://github.com/benjaminp/six.git#egg=six in /home/hawk/.virtualenvs/tempenv-3321664538cc/lib/python3.6/site-packages ``` And a Dockerfile which reproduces: ```dockerfile FROM python:3.6-alpine3.7 ENV PYTHONUNBUFFERED=1 ENV LC_ALL=en_US.UTF-8 RUN apk update \ && apk add git WORKDIR /app/ RUN set -ex \ && pip install --upgrade pip \ && pip install git+https://github.com/benjaminp/six.git#egg=six \ && pip install git+https://github.com/benjaminp/six.git#egg=six CMD ["/bin/bash"] ``` We can reproduce on our build machines, try this: ``` docker run -it circleci/python:2.7.13 cd ~ virtualenv env . env/bin/activate pip install -U pip pip install git+https://github.com/requests/requests.git#egg=requests pip install git+https://github.com/requests/requests.git#egg=requests ``` Here's my output: ``` ericely$ docker run -it circleci/python:2.7.13 $ cd ~ $ virtualenv env New python executable in /home/circleci/env/bin/python Installing setuptools, pip, wheel... done. $ $ . env/bin/activate (env) $ pip install -U pip Requirement already up-to-date: pip in ./env/lib/python2.7/site-packages (10.0.0) (env) $ pip list Package Version ---------- ------- pip 10.0.0 setuptools 39.0.1 wheel 0.31.0 (env) $ pip install git+https://github.com/requests/requests.git#egg=requests Collecting requests from git+https://github.com/requests/requests.git#egg=requests Cloning https://github.com/requests/requests.git to /tmp/pip-install-I8n5LX/requests Collecting chardet<3.1.0,>=3.0.2 (from requests) Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB) 100% |████████████████████████████████| 143kB 3.9MB/s Collecting idna<2.7,>=2.5 (from requests) Downloading https://files.pythonhosted.org/packages/27/cc/6dd9a3869f15c2edfab863b992838277279ce92663d334df9ecf5106f5c6/idna-2.6-py2.py3-none-any.whl (56kB) 100% |████████████████████████████████| 61kB 7.9MB/s Collecting urllib3<1.23,>=1.21.1 (from requests) Downloading https://files.pythonhosted.org/packages/63/cb/6965947c13a94236f6d4b8223e21beb4d576dc72e8130bd7880f600839b8/urllib3-1.22-py2.py3-none-any.whl (132kB) 100% |████████████████████████████████| 133kB 8.0MB/s Collecting certifi>=2017.4.17 (from requests) Downloading https://files.pythonhosted.org/packages/7c/e6/92ad559b7192d846975fc916b65f667c7b8c3a32bea7372340bfe9a15fa5/certifi-2018.4.16-py2.py3-none-any.whl (150kB) 100% |████████████████████████████████| 153kB 4.3MB/s Building wheels for collected packages: requests Running setup.py bdist_wheel for requests ... done Stored in directory: /tmp/pip-ephem-wheel-cache-F7Eu9c/wheels/8d/84/fa/1ded919cc5b46b899830a8f8d18817f59abde627aa07362b23 Successfully built requests Installing collected packages: chardet, idna, urllib3, certifi, requests Successfully installed certifi-2018.4.16 chardet-3.0.4 idna-2.6 requests-2.18.4 urllib3-1.22 (env) $ (env) $ pip install git+https://github.com/requests/requests.git#egg=requests Requirement already satisfied: requests from git+https://github.com/requests/requests.git#egg=requests in ./env/lib/python2.7/site-packages (2.18.4) Requirement already satisfied: idna<2.7,>=2.5 in ./env/lib/python2.7/site-packages (from requests) (2.6) Requirement already satisfied: urllib3<1.23,>=1.21.1 in ./env/lib/python2.7/site-packages (from requests) (1.22) Requirement already satisfied: certifi>=2017.4.17 in ./env/lib/python2.7/site-packages (from requests) (2018.4.16) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in ./env/lib/python2.7/site-packages (from requests) (3.0.4) Building wheels for collected packages: requests Exception: Traceback (most recent call last): File "/home/circleci/env/lib/python2.7/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/home/circleci/env/lib/python2.7/site-packages/pip/_internal/commands/install.py", line 305, in run session=session, autobuilding=True File "/home/circleci/env/lib/python2.7/site-packages/pip/_internal/wheel.py", line 773, in build python_tag=python_tag, File "/home/circleci/env/lib/python2.7/site-packages/pip/_internal/wheel.py", line 633, in _build_one python_tag=python_tag) File "/home/circleci/env/lib/python2.7/site-packages/pip/_internal/wheel.py", line 637, in _build_one_inside_env if self.__build_one(req, temp_dir.path, python_tag=python_tag): File "/home/circleci/env/lib/python2.7/site-packages/pip/_internal/wheel.py", line 663, in __build_one base_args = self._base_setup_args(req) File "/home/circleci/env/lib/python2.7/site-packages/pip/_internal/wheel.py", line 659, in _base_setup_args SETUPTOOLS_SHIM % req.setup_py File "/home/circleci/env/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 415, in setup_py assert self.source_dir, "No source dir for %s" % self AssertionError: No source dir for requests from git+https://github.com/requests/requests.git#egg=requests in ./env/lib/python2.7/site-packages (env) $ ``` @pfmoore This is an important core use-case which is broken. I'm looking into a fix right now. Also experiencing this issue @pradyunsg Cool, keep me posted - if there's anything I can help with let me know.
2018-04-18T04:21:31Z
[]
[]
Traceback (most recent call last): File "/home/p/local/lib/python3.5/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/home/p/local/lib/python3.5/site-packages/pip/_internal/commands/install.py", line 305, in run session=session, autobuilding=True File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 773, in build python_tag=python_tag, File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 633, in _build_one python_tag=python_tag) File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 637, in _build_one_inside_env if self.__build_one(req, temp_dir.path, python_tag=python_tag): File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 663, in __build_one base_args = self._base_setup_args(req) File "/home/p/local/lib/python3.5/site-packages/pip/_internal/wheel.py", line 659, in _base_setup_args SETUPTOOLS_SHIM % req.setup_py File "/home/p/local/lib/python3.5/site-packages/pip/_internal/req/req_install.py", line 416, in setup_py assert self.source_dir, "No source dir for %s" % self AssertionError: No source dir for mypackage from git+ssh://git@example.com/mypackage.git#egg=mypackage in /home/p/local/lib/python3.5/site-packages
17,398
pypa/pip
pypa__pip-5526
45d3d424578931cf764490c6e033f716dfe9ca45
diff --git a/docs/conf.py b/docs/conf.py --- a/docs/conf.py +++ b/docs/conf.py @@ -127,6 +127,7 @@ extlinks = { 'issue': ('https://github.com/pypa/pip/issues/%s', '#'), 'pull': ('https://github.com/pypa/pip/pull/%s', 'PR #'), + 'pypi': ('https://pypi.org/project/%s', ''), } # -- Options for HTML output --------------------------------------------------
Can't run tests with py.test [Documented](https://pip.pypa.io/en/stable/development/#running-tests) way of running tests with just `py.test` doesn't work. ``` # py.test Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/_pytest/config.py", line 379, in _importconftest mod = conftestpath.pyimport() File "/usr/local/lib/python2.7/dist-packages/py/_path/local.py", line 668, in pyimport __import__(modname) File "/usr/local/lib/python2.7/dist-packages/_pytest/assertion/rewrite.py", line 212, in load_module py.builtin.exec_(co, mod.__dict__) File "/usr/local/lib/python2.7/dist-packages/py/_builtin.py", line 221, in exec_ exec2(obj, globals, locals) File "<string>", line 7, in exec2 File "/root/pip/tests/conftest.py", line 10, in <module> import pip._internal ImportError: No module named _internal ERROR: could not load /root/pip/tests/conftest.py ``` `tox` runs fine though.
You need to add src to the Python path: `PYTHONPATH=$PWD/src py.test` And yes the documentation should be updated :P. Command helps, but tests fail - https://pastebin.mozilla.org/9073260 - which is strange, considering that builds are green. I think the tests ran invoked the system pip. (`/usr/bin/pip` on line 58 makes me think so) I, for one, use the tox environment itself -- with `./.tox/py36/bin/py.test` aliased to `tox-pytest` (and a `tox-pip` as well). Also, to pass arguments to pytest through tox, you can run tests as `tox -e py36 -- {args}` and they'll get passed to the underlying pytest call. `.tox/py27/bin/py.test tests/functional/test_install_reqs.py` fixes 2 tests and 3 still fail - https://pastebin.mozilla.org/?diff=9073266 `tox -e py27 -- tests/functional/test_install_reqs.py` gives the same result. One of them seems to be because SVN isn't installed. The other seems to be a more esoteric error. One of them is an expected failure. @techtonik Anything actionable here? (note: the documentation has been updated to say install everything in `dev-requirements.txt`) Closing due to lack of activity. @pradyunsg actionable - open https://pip.pypa.io/en/stable/development/#running-tests and run tests with all ways to confirm it is broken for you too. i believe all thats needed is a note to run the test against the installed pip ^^
2018-06-23T11:21:46Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/_pytest/config.py", line 379, in _importconftest mod = conftestpath.pyimport() File "/usr/local/lib/python2.7/dist-packages/py/_path/local.py", line 668, in pyimport __import__(modname) File "/usr/local/lib/python2.7/dist-packages/_pytest/assertion/rewrite.py", line 212, in load_module py.builtin.exec_(co, mod.__dict__) File "/usr/local/lib/python2.7/dist-packages/py/_builtin.py", line 221, in exec_ exec2(obj, globals, locals) File "<string>", line 7, in exec2 File "/root/pip/tests/conftest.py", line 10, in <module> import pip._internal ImportError: No module named _internal
17,411
pypa/pip
pypa__pip-5559
c39a51003ec659cd19c49f061ca44eeb3634fbfd
diff --git a/src/pip/_internal/wheel.py b/src/pip/_internal/wheel.py --- a/src/pip/_internal/wheel.py +++ b/src/pip/_internal/wheel.py @@ -163,7 +163,7 @@ def message_about_scripts_not_on_PATH(scripts): # We don't want to warn for directories that are on PATH. not_warn_dirs = [ os.path.normcase(i).rstrip(os.sep) for i in - os.environ["PATH"].split(os.pathsep) + os.environ.get("PATH", "").split(os.pathsep) ] # If an executable sits with sys.executable, we don't warn for it. # This covers the case of venv invocations without activating the venv.
Missing PATH environment causes pip to put things into an inconsistent state when upgrading a package **Environment** * pip version: 10.0.1 * Python version: 2.7.12 * OS: Ubuntu 16.0.4 <!-- Feel free to add more information about your environment here --> **Description** <!-- A clear and concise description of what the bug is. --> If the `PATH` environment variable is missing, pip fails to upgrade a package correctly. `pip list` will report the new version in installed, but the old version will be imported from python **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> Pip does not need `PATH` to be set to function - it is only used as a check to display a warning message. If it is missing, the check should be skipped, or a warning that the check could not be performed should be emitted. **How to Reproduce** <!-- Describe the steps to reproduce this bug. --> 1. Create a virtual environment, and install some package that you can programatically determine the version of 2. unset PATH 3. Use pip (specifying the full path to the executable in the virtual environment) to install a different version. Observe the stack trace 4. run `pip list` observe that it reports the new version of the package is installed 5. start a python REPL, observe that the version of the package you can actually import is the old version **Output** Install django 1.9 and observe that we get the expected version when importing in the REPL ``` oj:~$ mkvirtualenv pip-path-error Running virtualenv with interpreter /usr/bin/python2 New python executable in /home/oj/virtualenv/pip-path-error/bin/python2 Also creating executable in /home/oj/virtualenv/pip-path-error/bin/python Please make sure you remove any previous custom paths from your /home/oj/.pydistutils.cfg file. Installing setuptools, pkg_resources, pip, wheel...done. (pip-path-error)oj:~$ pip install django==1.9 Looking in indexes: https://oliver.jeeves:<password>@<internal_pypi_server>/repository/pypi/simple Collecting django==1.9 Downloading https://<internal_pypi_server>/repository/pypi/packages/ea/9b/b5a6360b3dfcd88d4bad70f59da26cbde4bdec395a31bb26dc840e806a50/Django-1.9-py2.py3-none-any.whl (6.6MB) 100% |████████████████████████████████| 6.6MB 5.2MB/s Installing collected packages: django Successfully installed django-1.9 (pip-path-error)oj:~$ python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (1, 9, 0, 'final', 0) >>> ``` Unset PATH and try upgrading django ``` (pip-path-error)oj:~$ unset PATH (pip-path-error)oj:~$ /home/oj/virtualenv/pip-path-error/bin/pip install --upgrade django==1.11 Looking in indexes: https://oliver.jeeves:<password>@<internal_pypi_server>/repository/pypi/simple Collecting django==1.11 Using cached https://<internal_pypi_server>/repository/pypi/packages/47/a6/078ebcbd49b19e22fd560a2348cfc5cec9e5dcfe3c4fad8e64c9865135bb/Django-1.11-py2.py3-none-any.whl Collecting pytz (from django==1.11) Downloading https://<internal_pypi_server>/repository/pypi/packages/30/4e/27c34b62430286c6d59177a0842ed90dc789ce5d1ed740887653b898779a/pytz-2018.5-py2.py3-none-any.whl (510kB) 100% |████████████████████████████████| 512kB 18.6MB/s Installing collected packages: pytz, django Found existing installation: Django 1.9 Uninstalling Django-1.9: Successfully uninstalled Django-1.9 Rolling back uninstall of Django Exception: Traceback (most recent call last): File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/commands/install.py", line 335, in run use_user_site=options.use_user_site, File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/req/__init__.py", line 49, in install_given_reqs **kwargs File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 748, in install use_user_site=use_user_site, pycompile=pycompile, File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 961, in move_wheel_files warn_script_location=warn_script_location, File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/wheel.py", line 466, in move_wheel_files msg = message_about_scripts_not_on_PATH(generated_console_scripts) File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/wheel.py", line 167, in message_about_scripts_not_on_PATH os.path.normcase(i) for i in os.environ["PATH"].split(os.pathsep) File "/home/oj/virtualenv/pip-path-error/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'PATH' ``` Observe that now `pip list` reports the new version, although that's not the version you get when you actually try to import it ``` (pip-path-error)oj:~$ /home/oj/virtualenv/pip-path-error/bin/pip list Package Version ------------- ------- Django 1.11 pip 10.0.1 pkg-resources 0.0.0 pytz 2018.5 setuptools 39.2.0 wheel 0.31.1 (pip-path-error)oj:~$ /home/oj/virtualenv/pip-path-error/bin/python Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import django >>> django.VERSION (1, 9, 0, 'final', 0) >>> ```
Thanks for filing this issue @SpoonMeiser! :) The required fix would be the following; with tests to verify. :) ```diff diff --git a/src/pip/_internal/wheel.py b/src/pip/_internal/wheel.py index 66738597..509501be 100644 --- a/src/pip/_internal/wheel.py +++ b/src/pip/_internal/wheel.py @@ -163,7 +163,7 @@ def message_about_scripts_not_on_PATH(scripts): # We don't want to warn for directories that are on PATH. not_warn_dirs = [ os.path.normcase(i).rstrip(os.sep) for i in - os.environ["PATH"].split(os.pathsep) + os.environ.get("PATH", "").split(os.pathsep) ] # If an executable sits with sys.executable, we don't warn for it. # This covers the case of venv invocations without activating the venv. ``` That was pretty much what I was going to propose - just having a few issues getting the tests running locally @SpoonMeiser Please do let me know what issues you're facing with running tests locally. I'm personally trying to figure out how to make it easier for new contributors to get started with pip's development, so it would be helpful to know what issues you're facing. As a bonus, I might be able to help you resolve them. :) The problems I was having are: 1. `pip install -e .` wasn't working - but I think this might have been a problem with our internal pypi server; reverting to the 'global' one solved that 2. I expected `python setup.py test` to install test dependencies, but it didn't, and I'm not sure how I'm supposed to find out what they are other than repeatedly running it and installing dependencies it complains about. 3. Eventually taking the time to read your development doc, and using tox, I found that running `tox -e py27 tests/unit/test_wheel.py` fails, but `tox -e py27 tests/unit` passes, which doesn't seem right, although I admit I'm not at all familiar with tox. I do have change to submit now though
2018-07-02T12:32:43Z
[]
[]
Traceback (most recent call last): File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/commands/install.py", line 335, in run use_user_site=options.use_user_site, File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/req/__init__.py", line 49, in install_given_reqs **kwargs File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 748, in install use_user_site=use_user_site, pycompile=pycompile, File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 961, in move_wheel_files warn_script_location=warn_script_location, File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/wheel.py", line 466, in move_wheel_files msg = message_about_scripts_not_on_PATH(generated_console_scripts) File "/home/oj/virtualenv/pip-path-error/local/lib/python2.7/site-packages/pip/_internal/wheel.py", line 167, in message_about_scripts_not_on_PATH os.path.normcase(i) for i in os.environ["PATH"].split(os.pathsep) File "/home/oj/virtualenv/pip-path-error/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'PATH'
17,412
pypa/pip
pypa__pip-5764
0d9c05ec32bc420547d846a780507d44acd9a4a6
diff --git a/src/pip/_internal/cli/base_command.py b/src/pip/_internal/cli/base_command.py --- a/src/pip/_internal/cli/base_command.py +++ b/src/pip/_internal/cli/base_command.py @@ -170,12 +170,14 @@ def main(self, args): return UNKNOWN_ERROR finally: - # Check if we're using the latest version of pip available - skip_version_check = ( - options.disable_pip_version_check or - getattr(options, "no_index", False) + allow_version_check = ( + # Does this command have the index_group options? + hasattr(options, "no_index") and + # Is this command allowed to perform this check? + not (options.disable_pip_version_check or options.no_index) ) - if not skip_version_check: + # Check if we're using the latest version of pip available + if allow_version_check: session = self._build_session( options, retries=0, diff --git a/src/pip/_internal/utils/outdated.py b/src/pip/_internal/utils/outdated.py --- a/src/pip/_internal/utils/outdated.py +++ b/src/pip/_internal/utils/outdated.py @@ -22,16 +22,25 @@ class SelfCheckState(object): def __init__(self, cache_dir): - self.statefile_path = os.path.join(cache_dir, "selfcheck.json") + self.state = {} + self.statefile_path = None - # Load the existing state - try: - with open(self.statefile_path) as statefile: - self.state = json.load(statefile)[sys.prefix] - except (IOError, ValueError, KeyError): - self.state = {} + # Try to load the existing state + if cache_dir: + self.statefile_path = os.path.join(cache_dir, "selfcheck.json") + try: + with open(self.statefile_path) as statefile: + self.state = json.load(statefile)[sys.prefix] + except (IOError, ValueError, KeyError): + # Explicitly suppressing exceptions, since we don't want to + # error out if the cache file is invalid. + pass def save(self, pypi_version, current_time): + # If we do not have a path to cache in, don't bother saving. + if not self.statefile_path: + return + # Check to make sure that we own the directory if not check_path_owner(os.path.dirname(self.statefile_path)): return
AttributeError: Values instance has no attribute 'find_links' **Environment** * pip version: pip 10.0.1 from c:\python27\lib\site-packages\pip (python 2.7) * Python version: 2.7.14 * OS: Windows 10 **Description** ``` $ pip config list --verbose For variant 'global', will try loading 'C:\ProgramData\pip\pip.ini' For variant 'user', will try loading 'C:\Users\<user>\pip\pip.ini' For variant 'user', will try loading 'C:\Users\<user>\AppData\Roaming\pip\pip.ini' global.cert='C:\\ProgramData\\pip\\ca-bundle.crt' global.index-url='...........' install.no-binary='.......' There was an error checking the latest version of pip Traceback (most recent call last): File "c:\python27\lib\site-packages\pip\_internal\utils\outdated.py", line 125, in pip_version_check find_links=options.find_links, AttributeError: Values instance has no attribute 'find_links' ``` **Expected behavior** No exception **How to Reproduce** 1. Execute `pip config --list --verbose` Fix the pip version check when using --no-cache-dir <!--- Thank you for your soon to be pull request. Before you submit this, please double check to make sure that you've added a news file fragment. In pip we generate our NEWS.rst from multiple news fragment files, and all pull requests require either a news file fragment or a marker to indicate they don't require one. To read more about adding a news file fragment for your PR, please check out our documentation at: https://pip.pypa.io/en/latest/development/contributing/#adding-a-news-entry --> The pip version check will now work correctly when using ``--no-cache-dir``. Fixes #5679
I can confirm on Linux also pip -vvv config Need an action (edit, get, list, set, unset) to perform. There was an error checking the latest version of pip Traceback (most recent call last): File "/opt/our_custom_path/lib/python2.7/site-packages/pip/_internal/utils/outdated.py", line 125, in pip_version_check find_links=options.find_links, AttributeError: Values instance has no attribute 'find_links' pip -V pip 10.0.1 from /opt/our_custom_path/lib/python2.7/site-packages/pip (python 2.7) I confirm :+1: Thanks for the report. I just tried this on a fresh Ubuntu 14.04 system, I didn't get any errors. Could someone explain how to reproduce this? There is something strange here: I'm only getting the error with my system's pip (on archlinux) and not in a fresh venv, but the only diff between the two are in the "pip/_vendor" which is unlikely to explain the difference... Ok: in a fresh venv we are using a different file for `pip-selfcheck.json` (https://github.com/pypa/pip/blob/10.0.1/src/pip/_internal/utils/outdated.py#L26) and not the global one (https://github.com/pypa/pip/blob/10.0.1/src/pip/_internal/utils/outdated.py#L51). @pradyunsg : removing the `pip-selfcheck.json` should trigger the issue @xavfernandez FWIW, we simplified the two file mechanism in #5419 -- that might make this harder to reproduce on `master`. Is this still an issue on `master`? I've tried on a pyenv installed Python 3.7 on MacOS and it doesn't seem to be erroring for me, in a venv or outside of it. I have empty configuration files however. Could you provide the exact config file contents that is causing this? :/ @pradyunsg the issue still exists on `master`. You don't need a config file, you only need to end up here: https://github.com/pypa/pip/blob/96f9fcc/src/pip/_internal/utils/outdated.py#L103 (so either an old date in `selfcheck.json` or no `selfcheck.json` at all). The issue being that `options` won't contain a `find_links` key which is expected since this option is only present in [index_group](https://github.com/pypa/pip/blob/96f9fcc4a02a1e7521d807899a2723b31559cdde/src/pip/_internal/cmdoptions.py#L610) which in turn is only available in `wheel`, `install`, `list` and `download` commands. Thus we get similar traceback for `freeze`: <details> ``` $ pip freeze -v Created temporary directory: /tmp/pip-ephem-wheel-cache-e138jnjj There was an error checking the latest version of pip Traceback (most recent call last): File "/home/xfernandez/.virtualenvs/tmp-475844793f0ebbc/lib/python3.6/site-packages/pip/_internal/utils/outdated.py", line 107, in pip_version_check index_urls=[options.index_url] + options.extra_index_urls, AttributeError: 'Values' object has no attribute 'index_url' ``` </details> and `show`: <details> ``` $ pip show pip -v Name: pip Version: 18.0.dev0 Summary: The PyPA recommended tool for installing Python packages. Home-page: https://pip.pypa.io/ Author: The pip developers Author-email: pypa-dev@groups.google.com License: MIT Location: /home/xfernandez/.virtualenvs/tmp-475844793f0ebbc/lib/python3.6/site-packages Requires: Required-by: Metadata-Version: 2.1 Installer: pip Classifiers: Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: MIT License Topic :: Software Development :: Build Tools Programming Language :: Python Programming Language :: Python :: 2 Programming Language :: Python :: 2.7 Programming Language :: Python :: 3 Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: Implementation :: CPython Programming Language :: Python :: Implementation :: PyPy Entry-points: [console_scripts] pip = pip._internal:main pip3 = pip._internal:main pip3.6 = pip._internal:main There was an error checking the latest version of pip Traceback (most recent call last): File "/home/xfernandez/.virtualenvs/tmp-475844793f0ebbc/lib/python3.6/site-packages/pip/_internal/utils/outdated.py", line 106, in pip_version_check find_links=options.find_links, AttributeError: 'Values' object has no attribute 'find_links' ``` </details> Maybe we should restrict pip selfcheck to commands with `index_group` options available ? Ah. Right. So, that seems like an issue with the self check logic. Your suggestion makes sense to me. It'll be an interesting task to implement it though. ;) The self-checking logic is strange. 1. It uses one global state file outside of `virtualenv` for caching `pip` version checks. 2. It uses PackageFinder component where it could just query some URL with latest tag. 3. It checks `installed version` instead of checking itself. Added request to PyPI to simplify lookups by using just a single request- https://github.com/pypa/warehouse/issues/4663 Reproduced this. Working on this. Could this patch please be merged? It fixes two of the three tracebacks reported in #5679 I wasn't able to reproduce https://github.com/pypa/pip/issues/5679#issuecomment-409174290 . @segevfiner could you share how to reproduce that from scratch? > I wasn't able to reproduce #5679 (comment) . @segevfiner could you share how to reproduce that from scratch? `pip show --verbose --no-cache-dir requests` after merging this.
2018-09-05T07:26:37Z
[]
[]
Traceback (most recent call last): File "c:\python27\lib\site-packages\pip\_internal\utils\outdated.py", line 125, in pip_version_check find_links=options.find_links, AttributeError: Values instance has no attribute 'find_links'
17,417
pypa/pip
pypa__pip-5931
169cd10b3fe15747afc1ea5c582ff0cb3d2b8052
diff --git a/src/pip/_internal/vcs/mercurial.py b/src/pip/_internal/vcs/mercurial.py --- a/src/pip/_internal/vcs/mercurial.py +++ b/src/pip/_internal/vcs/mercurial.py @@ -45,7 +45,7 @@ def fetch_new(self, dest, url, rev_options): def switch(self, dest, url, rev_options): repo_config = os.path.join(dest, self.dirname, 'hgrc') - config = configparser.SafeConfigParser() + config = configparser.RawConfigParser() try: config.read(repo_config) config.set('paths', 'default', url)
pip uses deprecated SafeConfigParser * Pip version: 9.0.1 * Python version: 3.6.1 * Operating system: Mac OS X 10.12.4 ### Description: With `error::DeprecationWarning` in `PYTHONWARNINGS`: ``` pip uninstall -y faker /Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/pep425tags.py:260: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp Exception: Traceback (most recent call last): File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/commands/uninstall.py", line 76, in run requirement_set.uninstall(auto_confirm=options.yes) File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/req/req_set.py", line 346, in uninstall req.uninstall(auto_confirm=auto_confirm) File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/req/req_install.py", line 732, in uninstall config = configparser.SafeConfigParser(**options) File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/versions/python3.6/lib/python3.6/configparser.py", line 1212, in __init__ DeprecationWarning, stacklevel=2 DeprecationWarning: The SafeConfigParser class has been renamed to ConfigParser in Python 3.2. This alias will be removed in future versions. Use ConfigParser directly instead. ```
Hey @dchudz! Thanks for filing this issue! I don't see this exact same line in master but there's definitely something similar to this in the codebase today. This issue is a good starting point for anyone who wants to help out with pip's development -- it's simple and the process of fixing this should be a good introduction to pip's development workflow. :) This particular SafeConfigParser was removed in d64b871d97f64fa10ca5a3f390d14fb35d761390 There is however another one ``` src/pip/_internal/vcs/mercurial.py 36: config = configparser.SafeConfigParser() ``` Ah thanks/sorry @brycepg! I should have checked master and not just the latest release. > There is however another one Great! I guess that is still something that needs fixing. :)
2018-10-27T10:29:41Z
[]
[]
Traceback (most recent call last): File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/commands/uninstall.py", line 76, in run requirement_set.uninstall(auto_confirm=options.yes) File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/req/req_set.py", line 346, in uninstall req.uninstall(auto_confirm=auto_confirm) File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/.tox/py36-full/lib/python3.6/site-packages/pip/req/req_install.py", line 732, in uninstall config = configparser.SafeConfigParser(**options) File "/Users/davidchudzicki/.cache/hypothesis-build-runtimes/versions/python3.6/lib/python3.6/configparser.py", line 1212, in __init__ DeprecationWarning, stacklevel=2 DeprecationWarning: The SafeConfigParser class has been renamed to ConfigParser in Python 3.2. This alias will be removed in future versions. Use ConfigParser directly instead.
17,431
pypa/pip
pypa__pip-6008
b8ee4a648ea8b7535d1a626d4f6e5ba922522242
diff --git a/src/pip/_internal/locations.py b/src/pip/_internal/locations.py --- a/src/pip/_internal/locations.py +++ b/src/pip/_internal/locations.py @@ -156,8 +156,9 @@ def distutils_scheme(dist_name, user=False, home=None, root=None, # or user base for installations during finalize_options() # ideally, we'd prefer a scheme class that has no side-effects. assert not (user and prefix), "user={} prefix={}".format(user, prefix) + assert not (home and prefix), "home={} prefix={}".format(home, prefix) i.user = user or i.user - if user: + if user or home: i.prefix = "" i.prefix = prefix or i.prefix i.home = home or i.home
DistutilsOptionError with --target and prefix or exec-prefix * Pip version: 9.0.1 * Python version: 2.7.12 * Operating System: macOS 10.12.1 ### Description: Having installed Python 2.7 using Homebrew, I'm unable to install packages using `--target' ### What I've run: ``` $ python2.7 -m pip install -t foo requests Collecting requests Using cached requests-2.11.1-py2.py3-none-any.whl Installing collected packages: requests Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 247, in move_wheel_files prefix=prefix, File "/usr/local/lib/python2.7/site-packages/pip/locations.py", line 153, in distutils_scheme i.finalize_options() File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/command/install.py", line 264, in finalize_options "must supply either home or prefix/exec-prefix -- not both" DistutilsOptionError: must supply either home or prefix/exec-prefix -- not both ``` Obviously, I didn't supply home nor prefix, so the error message is confusing.
See pull #4103 Closing to move a bunch of related issues to a single issue: #4390. This issue still exists. ``` $ python2.7 -m pip -V pip 18.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7) $ python2.7 -m pip install --target out requests Collecting requests Downloading https://files.pythonhosted.org/packages/ff/17/5cbb026005115301a8fb2f9b0e3e8d32313142fe8b617070e7baad20554f/requests-2.20.1-py2.py3-none-any.whl (57kB) 100% |████████████████████████████████| 61kB 400kB/s Collecting certifi>=2017.4.17 (from requests) Using cached https://files.pythonhosted.org/packages/56/9d/1d02dd80bc4cd955f98980f28c5ee2200e1209292d5f9e9cc8d030d18655/certifi-2018.10.15-py2.py3-none-any.whl Collecting idna<2.8,>=2.5 (from requests) Using cached https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl Collecting urllib3<1.25,>=1.21.1 (from requests) Using cached https://files.pythonhosted.org/packages/62/00/ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/urllib3-1.24.1-py2.py3-none-any.whl Collecting chardet<3.1.0,>=3.0.2 (from requests) Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl Installing collected packages: certifi, idna, urllib3, chardet, requests Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip/_internal/cli/base_command.py", line 143, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip/_internal/commands/install.py", line 366, in run use_user_site=options.use_user_site, File "/usr/local/lib/python2.7/site-packages/pip/_internal/req/__init__.py", line 49, in install_given_reqs **kwargs File "/usr/local/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 760, in install use_user_site=use_user_site, pycompile=pycompile, File "/usr/local/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 382, in move_wheel_files warn_script_location=warn_script_location, File "/usr/local/lib/python2.7/site-packages/pip/_internal/wheel.py", line 215, in move_wheel_files prefix=prefix, File "/usr/local/lib/python2.7/site-packages/pip/_internal/locations.py", line 165, in distutils_scheme i.finalize_options() File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/command/install.py", line 264, in finalize_options "must supply either home or prefix/exec-prefix -- not both" DistutilsOptionError: must supply either home or prefix/exec-prefix -- not both ``` Note, I have not specified `prefix` nor `home`. There's something about the Homebrew install of Python that causes it to set the prefix. I think it's this: ``` $ cat /usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/distutils.cfg [install] prefix=/usr/local [build_ext] include_dirs=/usr/local/include:/usr/local/opt/openssl/include:/usr/local/opt/sqlite/include library_dirs=/usr/local/lib:/usr/local/opt/openssl/lib:/usr/local/opt/sqlite/lib ``` As a result, `pip install --target` is simply broken on vanilla Homebrew installs (or any install that sets a prefix). Does it work when using `pip --isolated install --target`? > Does it work with `--isolated`? No, same error. From the code, it looks like `--isolated` will ignore distutils user configuration, but the global one will still get picked up. I think, similarly to when `user` is used, `distutils_scheme` should ignore the install prefix when `home` is used: ```diff src/pip/_internal/locations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git i/src/pip/_internal/locations.py w/src/pip/_internal/locations.py index 89a3656b..72fe7c6f 100644 --- i/src/pip/_internal/locations.py +++ w/src/pip/_internal/locations.py @@ -170,7 +170,7 @@ def distutils_scheme(dist_name, user=False, home=None, root=None, # ideally, we'd prefer a scheme class that has no side-effects. assert not (user and prefix), "user={} prefix={}".format(user, prefix) i.user = user or i.user - if user: + if user or home: i.prefix = "" i.prefix = prefix or i.prefix i.home = home or i.home ``` The `assert` line should probably be updated too. Confirmed - that one patch does address the issue. ``` pip 18.1 $ python2.7 -m pip -V pip 18.1 from /Users/jaraco/code/public/pypa/pip/src/pip (python 2.7) pip 18.1 $ python2.7 -m pip install --target out requests Collecting requests Using cached https://files.pythonhosted.org/packages/ff/17/5cbb026005115301a8fb2f9b0e3e8d32313142fe8b617070e7baad20554f/requests-2.20.1-py2.py3-none-any.whl Collecting idna<2.8,>=2.5 (from requests) Using cached https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl Collecting urllib3<1.25,>=1.21.1 (from requests) Using cached https://files.pythonhosted.org/packages/62/00/ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/urllib3-1.24.1-py2.py3-none-any.whl Collecting chardet<3.1.0,>=3.0.2 (from requests) Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl Collecting certifi>=2017.4.17 (from requests) Using cached https://files.pythonhosted.org/packages/56/9d/1d02dd80bc4cd955f98980f28c5ee2200e1209292d5f9e9cc8d030d18655/certifi-2018.10.15-py2.py3-none-any.whl Installing collected packages: idna, urllib3, chardet, certifi, requests Exception: Traceback (most recent call last): File "/Users/jaraco/code/public/pypa/pip/src/pip/_internal/cli/base_command.py", line 143, in main status = self.run(options, args) File "/Users/jaraco/code/public/pypa/pip/src/pip/_internal/commands/install.py", line 366, in run use_user_site=options.use_user_site, File "/Users/jaraco/code/public/pypa/pip/src/pip/_internal/req/__init__.py", line 49, in install_given_reqs **kwargs File "/Users/jaraco/code/public/pypa/pip/src/pip/_internal/req/req_install.py", line 760, in install use_user_site=use_user_site, pycompile=pycompile, File "/Users/jaraco/code/public/pypa/pip/src/pip/_internal/req/req_install.py", line 382, in move_wheel_files warn_script_location=warn_script_location, File "/Users/jaraco/code/public/pypa/pip/src/pip/_internal/wheel.py", line 215, in move_wheel_files prefix=prefix, File "/Users/jaraco/code/public/pypa/pip/src/pip/_internal/locations.py", line 165, in distutils_scheme i.finalize_options() File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/command/install.py", line 264, in finalize_options "must supply either home or prefix/exec-prefix -- not both" DistutilsOptionError: must supply either home or prefix/exec-prefix -- not both pip 18.1 $ git stash pop HEAD detached at 18.1 Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: src/pip/_internal/locations.py no changes added to commit (use "git add" and/or "git commit -a") Dropped refs/stash@{0} (2c685ea2bf964f8475f09552556b800a693f1201) pip 18.1 $ git diff diff --git a/src/pip/_internal/locations.py b/src/pip/_internal/locations.py index 183aaa39..a4c79135 100644 --- a/src/pip/_internal/locations.py +++ b/src/pip/_internal/locations.py @@ -157,7 +157,7 @@ def distutils_scheme(dist_name, user=False, home=None, root=None, # ideally, we'd prefer a scheme class that has no side-effects. assert not (user and prefix), "user={} prefix={}".format(user, prefix) i.user = user or i.user - if user: + if user or home: i.prefix = "" i.prefix = prefix or i.prefix i.home = home or i.home pip 18.1 $ python2.7 -m pip install --target out requests Collecting requests Using cached https://files.pythonhosted.org/packages/ff/17/5cbb026005115301a8fb2f9b0e3e8d32313142fe8b617070e7baad20554f/requests-2.20.1-py2.py3-none-any.whl Collecting idna<2.8,>=2.5 (from requests) Using cached https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl Collecting urllib3<1.25,>=1.21.1 (from requests) Using cached https://files.pythonhosted.org/packages/62/00/ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/urllib3-1.24.1-py2.py3-none-any.whl Collecting chardet<3.1.0,>=3.0.2 (from requests) Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl Collecting certifi>=2017.4.17 (from requests) Using cached https://files.pythonhosted.org/packages/56/9d/1d02dd80bc4cd955f98980f28c5ee2200e1209292d5f9e9cc8d030d18655/certifi-2018.10.15-py2.py3-none-any.whl Installing collected packages: idna, urllib3, chardet, certifi, requests Successfully installed certifi-2018.10.15 chardet-3.0.4 idna-2.7 requests-2.20.1 urllib3-1.24.1 ```
2018-11-12T16:12:33Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python2.7/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python2.7/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python2.7/site-packages/pip/wheel.py", line 247, in move_wheel_files prefix=prefix, File "/usr/local/lib/python2.7/site-packages/pip/locations.py", line 153, in distutils_scheme i.finalize_options() File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/command/install.py", line 264, in finalize_options "must supply either home or prefix/exec-prefix -- not both" DistutilsOptionError: must supply either home or prefix/exec-prefix -- not both
17,437
pypa/pip
pypa__pip-6171
085e7403b2f405bcb7e475b7bcc40a4659a833a4
diff --git a/src/pip/_internal/wheel.py b/src/pip/_internal/wheel.py --- a/src/pip/_internal/wheel.py +++ b/src/pip/_internal/wheel.py @@ -840,12 +840,6 @@ def build( newly built wheel, in preparation for installation. :return: True if all the wheels built correctly. """ - # TODO: This check fails if --no-cache-dir is set. And yet we - # might be able to build into the ephemeral cache, surely? - building_is_possible = self._wheel_dir or ( - autobuilding and self.wheel_cache.cache_dir - ) - assert building_is_possible buildset = [] format_control = self.finder.format_control @@ -884,6 +878,13 @@ def build( if not buildset: return [] + # Is any wheel build not using the ephemeral cache? + if any(not ephem_cache for _, ephem_cache in buildset): + have_directory_for_build = self._wheel_dir or ( + autobuilding and self.wheel_cache.cache_dir + ) + assert have_directory_for_build + # TODO by @pradyunsg # Should break up this method into 2 separate methods.
assertion when using --no-cache-dir in 19.0 **Environment** * pip version: 19.0 * Python version: 3.6.7 * OS: Linux 50de819ca3ba 4.9.125-linuxkit #1 SMP Fri Sep 7 08:20:28 UTC 2018 x86_64 GNU/Linux Running in a dockerfile. **Description** The following command works with pip 18.1 and fails with 19.0. ``` pip3 install --no-cache-dir --upgrade -r requirements.txt ``` With 19.0, it fails with the following exception: ``` Exception: Traceback (most recent call last): File "/Users/scotts/.virtualenvs/python3/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 176, in main status = self.run(options, args) File "/Users/scotts/.virtualenvs/python3/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 346, in run session=session, autobuilding=True File "/Users/scotts/.virtualenvs/python3/lib/python3.6/site-packages/pip/_internal/wheel.py", line 848, in build assert building_is_possible AssertionError ``` Removing the `--no-cache-dir` flag causes the install to succeed. [requirements.txt](https://github.com/pypa/pip/files/2784417/requirements.txt)
Same thing happening with: `Python v3.6.8` `pip version 18.1` on [`Ubuntu:latest`](https://hub.docker.com/_/ubuntu/scans/library/ubuntu/latest) image. @snstanton what base image are you using? I'm seeing a similar issue on pip v18.1 as well I've got the exact same issue. on my side it seems it doesn't matter which package/distribution I try to install I'm seeing this even without `--no-cache-dir` set. It happens for all packages I try to install, even if they're already installed. - pip version: 19.0 - Python version: 3.6.0 - OS: Ubuntu 14.04.4 LTS (GNU/Linux 3.13.0-91-generic x86_64) I should note that in my case I'm seeing it when running `pip` with a combination of `sudo -H` and `bash -l -c`. ``` $ sudo -H bash -l -c "/data/virtualenvs/events_beta/bin/pip install hypothesis" Looking in indexes: https://pypi.org/simple, http://pypi.lan.cogtree.com/cogtree/simple/ Collecting hypothesis Downloading http://pypi.lan.cogtree.com/cogtree/simple/hypothesis/hypothesis-4.1.0-py3-none-any.whl (238kB) 100% |████████████████████████████████| 245kB 120.5MB/s Requirement already satisfied: attrs>=16.0.0 in /data/virtualenvs/events_beta/lib/python3.6/site-packages (from hypothesis) (18.2.0) Exception: Traceback (most recent call last): File "/data/virtualenvs/events_beta/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 176, in main status = self.run(options, args) File "/data/virtualenvs/events_beta/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 346, in run session=session, autobuilding=True File "/data/virtualenvs/events_beta/lib/python3.6/site-packages/pip/_internal/wheel.py", line 848, in build assert building_is_possible AssertionError ``` Running the same commands without `-l` on my `bash -c`, or without `bash -l -c` involved at all, it all works fine. ``` $ sudo -H bash -c "/data/virtualenvs/events_beta/bin/pip install hypothesis" Collecting hypothesis Downloading https://files.pythonhosted.org/packages/89/7b/d6206dcde963139daa03a1d85b0c3428cb3ebf2ae8de3244b14a63e22680/hypothesis-4.1.0.tar.gz (180kB) 100% |████████████████████████████████| 184kB 33.7MB/s Requirement already satisfied: attrs>=16.0.0 in /data/virtualenvs/events_beta/lib/python3.6/site-packages (from hypothesis) (18.2.0) Building wheels for collected packages: hypothesis Building wheel for hypothesis (setup.py) ... done Stored in directory: /root/.cache/pip/wheels/10/12/eb/4ab734432e8466d545c8501f531458845b45e8c4427d5367f9 Successfully built hypothesis Installing collected packages: hypothesis Successfully installed hypothesis-4.1.0 ``` Fascinatingly, if I run the same command without `sudo` or `bash` involved at all, it still fails with the same error, so it seems like it's some weird permissions issue maybe. ### Another workaround for some situations For people who hit this bug because virtualenv is automatically installing the latest version of pip, you can work around it by giving virtualenv the `--no-download` option, or setting `VIRTUALENV_NO_DOWNLOAD=1`. But be aware that this may give you a very old version of pip, depending on the last time you upgraded virtualenv. This also works with tox: `VIRTUALENV_NO_DOWNLOAD=1 tox`. for what it's worth : it also fails with same error if package is already installed: ``` gregory.starck@canon:~/tmp$ ./venv/bin/pip install --no-cache-dir six ; echo $? Looking in indexes: http://pypi:3141/root/ax/+simple/ Requirement already satisfied: six in ./venv/lib/python3.6/site-packages (1.12.0) Exception: Traceback (most recent call last): File "/home/gregory.starck/tmp/venv/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 176, in main status = self.run(options, args) File "/home/gregory.starck/tmp/venv/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 346, in run session=session, autobuilding=True File "/home/gregory.starck/tmp/venv/lib/python3.6/site-packages/pip/_internal/wheel.py", line 848, in build assert building_is_possible AssertionError 2 gregory.starck@canon:~/tmp$ ``` Ran into the same issue. Ended up pinning the pip version as a fix for now. `pip install --upgrade pip==18.1` Issue is with failing assert, so setting env PYTHONOPTIMIZE=1 (or with parameter -O) makes this error go away. Just tested it. This workaround works because python optimizes code removing all asserts as one of the things. Do not go for =2 (or -OO), as this removes docstrings and other tracebacks will appear - some code wants to operate on them. It looks like someone knew this might end up being an issue ([source](https://github.com/pypa/pip/blob/master/src/pip/_internal/wheel.py#L843)): ```python # TODO: This check fails if --no-cache-dir is set. And yet we # might be able to build into the ephemeral cache, surely? building_is_possible = self._wheel_dir or ( autobuilding and self.wheel_cache.cache_dir ) assert building_is_possible ``` https://github.com/pypa/pip/pull/5884 looks like this is a related change that could have caused this?
2019-01-23T04:25:10Z
[]
[]
Traceback (most recent call last): File "/Users/scotts/.virtualenvs/python3/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 176, in main status = self.run(options, args) File "/Users/scotts/.virtualenvs/python3/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 346, in run session=session, autobuilding=True File "/Users/scotts/.virtualenvs/python3/lib/python3.6/site-packages/pip/_internal/wheel.py", line 848, in build assert building_is_possible AssertionError
17,444
pypa/pip
pypa__pip-6253
fb944ab62f755e71204020bc5b9881367803e5ec
diff --git a/src/pip/_internal/wheel.py b/src/pip/_internal/wheel.py --- a/src/pip/_internal/wheel.py +++ b/src/pip/_internal/wheel.py @@ -779,6 +779,42 @@ def should_use_ephemeral_cache( return True +def get_legacy_build_wheel_path( + names, # type: List[str] + temp_dir, # type: str + req, # type: InstallRequirement + command_args, # type: List[str] + command_output, # type: str +): + # type: (...) -> Optional[str] + """ + Return the path to the wheel in the temporary build directory. + """ + # Sort for determinism. + names = sorted(names) + if not names: + # call_subprocess() ensures that the command output ends in a newline. + msg = ( + 'Failed building wheel for {} with args: {}\n' + 'Command output:\n{}' + '-----------------------------------------' + ).format(req.name, command_args, command_output) + logger.error(msg) + return None + if len(names) > 1: + # call_subprocess() ensures that the command output ends in a newline. + msg = ( + 'Found more than one file after building wheel for {} ' + 'with args: {}\n' + 'Names: {}\n' + 'Command output:\n{}' + '-----------------------------------------' + ).format(req.name, command_args, names, command_output) + logger.warning(msg) + + return os.path.join(temp_dir, names[0]) + + class WheelBuilder(object): """Build wheels from a RequirementSet.""" @@ -888,14 +924,21 @@ def _build_one_legacy(self, req, tempd, python_tag=None): wheel_args += ["--python-tag", python_tag] try: - call_subprocess(wheel_args, cwd=req.setup_py_dir, - show_stdout=False, spinner=spinner) + output = call_subprocess(wheel_args, cwd=req.setup_py_dir, + show_stdout=False, spinner=spinner) except Exception: spinner.finish("error") logger.error('Failed building wheel for %s', req.name) return None - # listdir's return value is sorted to be deterministic - return os.path.join(tempd, sorted(os.listdir(tempd))[0]) + names = os.listdir(tempd) + wheel_path = get_legacy_build_wheel_path( + names=names, + temp_dir=tempd, + req=req, + command_args=wheel_args, + command_output=output, + ) + return wheel_path def _clean_one(self, req): base_args = self._base_setup_args(req)
pip 19.0.2: IndexError when building wheel on osx **Environment** * pip version: 19.0.2 * Python version: 3.6 * OS: macos 10.13 * Platform: Travis-ci The error was observed on travis-ci build's using Miniconda with an environment that contains both conda and pip packages. **Description** It seems release 19.0.2 breaks something related to wheel building under certain circumstances. The problem started happening yesterday and it popped up exactly after 19.0.2 was released. The build was succeeding on 19.0.1, and as soon as 19.0.2 was available, the build started failing. See [successful build #10](https://travis-ci.com/gramaziokohler/robotic_assembly_workshop/builds/100329545) and [failed build #11](https://travis-ci.com/gramaziokohler/robotic_assembly_workshop/builds/100330616). After pinning pip back to 19.0.1, the build started working again. I don't have a clear idea of what exactly fails, but it seems to be related to `cvxpy` and its dependency [`scs`](https://github.com/cvxgrp/cvxpy/blob/master/setup.py#L70), but it is not clear to me if this is in any way connected to the root cause, or is only the visible side-effect. **How to Reproduce** 1. Build [using this travis file](https://github.com/gramaziokohler/robotic_assembly_workshop/blob/master/.travis.yml) 2. If pip version is not pinned, and it uses 19.0.2, an error occurs (see below for tracebacks and full output). **Output** The full build output is available directly on travis: https://travis-ci.com/gramaziokohler/robotic_assembly_workshop/builds/100338039 ``` Stored in directory: /Users/travis/Library/Caches/pip/wheels/1d/2f/99/1594715f229f93f235d8b370a3b6f16e2b00fbac1087a99902 Building wheel for scs (setup.py) ... done Exception: Traceback (most recent call last): File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 179, in main status = self.run(options, args) File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 355, in run session=session, autobuilding=True File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/wheel.py", line 980, in build python_tag=python_tag, File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/wheel.py", line 813, in _build_one python_tag=python_tag) File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/wheel.py", line 821, in _build_one_inside_env wheel_path = builder(req, temp_dir.path, python_tag=python_tag) File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/wheel.py", line 898, in _build_one_legacy return os.path.join(tempd, sorted(os.listdir(tempd))[0]) IndexError: list index out of range ```
The line causing this exception was added in PR #6236. It looks like before, the build in question (of scs) was hitting this line in `_build_one_inside_env()`: https://github.com/pypa/pip/pull/6236/files#diff-79304b3f74b6bf37043da4d96ccd3755L831 and then causing `_build_one_inside_env()` to return `None`. The line in question looked like this, so you can see the exception was being swallowed-- ```python except Exception: pass ``` Now, however, the exception is bubbling up without being handled because the code causing the `IndexError` was refactored out of that try-except block. If you look at the Travis log for the successful case (the older one), you can see here: https://travis-ci.com/gramaziokohler/robotic_assembly_workshop/builds/100329545#L284 that it says scs indeed failed to build: ``` Building wheel for scs (setup.py) ... done Running setup.py clean for scs Building wheel for future (setup.py) ... done Stored in directory: /Users/travis/Library/Caches/pip/wheels/0c/61/d2/d6b7317325828fbb39ee6ad559dbe4664d0896da4721bf379e Successfully built compas-assembly compas-rbe cvxpy future Failed to build scs ``` But this wasn't causing pip to error out before because of the exception swallowing I mentioned above.
2019-02-10T20:37:35Z
[]
[]
Traceback (most recent call last): File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 179, in main status = self.run(options, args) File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 355, in run session=session, autobuilding=True File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/wheel.py", line 980, in build python_tag=python_tag, File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/wheel.py", line 813, in _build_one python_tag=python_tag) File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/wheel.py", line 821, in _build_one_inside_env wheel_path = builder(req, temp_dir.path, python_tag=python_tag) File "/Users/travis/miniconda3/envs/workshop/lib/python3.6/site-packages/pip/_internal/wheel.py", line 898, in _build_one_legacy return os.path.join(tempd, sorted(os.listdir(tempd))[0]) IndexError: list index out of range
17,451
pypa/pip
pypa__pip-6336
5f3c56e1889ccafe49633e7bc7871b3b34ce2a8a
diff --git a/src/pip/_internal/req/constructors.py b/src/pip/_internal/req/constructors.py --- a/src/pip/_internal/req/constructors.py +++ b/src/pip/_internal/req/constructors.py @@ -325,7 +325,8 @@ def install_req_from_req_string( PyPI.file_storage_domain, TestPyPI.file_storage_domain, ] - if req.url and comes_from.link.netloc in domains_not_allowed: + if (req.url and comes_from and comes_from.link and + comes_from.link.netloc in domains_not_allowed): # Explicitly disallow pypi packages that depend on external urls raise InstallationError( "Packages installed from PyPI cannot depend on packages "
AttributeError: 'NoneType' object has no attribute 'netloc' **Environment** * pip version: 18.1 * Python version: 3.6 * OS: linux **Description** I am using a fresh conda environment (most packages from conda-forge), pip 18.1, python 3.6, and linux. I am utilizing the new PEP508 syntax for installing private packages from our internal gitlab server (anonymized below). I added some print statements that I hope will be helpful: ``` $ pip install -e . Obtaining file:///nas/home/broot/Programs/tools/catutils req: shapely comes_from: catutils==0.15.dev1 from file:///nas/home/broot/Programs/tools/catutils req: netCDF4 comes_from: catutils==0.15.dev1 from file:///nas/home/broot/Programs/tools/catutils req: aershp>=0.10 comes_from: catutils==0.15.dev1 from file:///nas/home/broot/Programs/tools/catutils req: numpy!=1.10,!=1.11.0 comes_from: catutils==0.15.dev1 from file:///nas/home/broot/Programs/tools/catutils req: scipy comes_from: catutils==0.15.dev1 from file:///nas/home/broot/Programs/tools/catutils req: GDAL comes_from: catutils==0.15.dev1 from file:///nas/home/broot/Programs/tools/catutils Requirement already satisfied: shapely in /rd22/scratch/broot/miniconda/envs/py3k/lib/python3.6/site-packages (from catutils==0.15.dev1) (1.6.4.post1) Requirement already satisfied: netCDF4 in /rd22/scratch/broot/miniconda/envs/py3k/lib/python3.6/site-packages (from catutils==0.15.dev1) (1.4.1) req: numpy>=1.7 comes_from: netCDF4 in /rd22/scratch/broot/miniconda/envs/py3k/lib/python3.6/site-packages (from catutils==0.15.dev1) req: cftime comes_from: netCDF4 in /rd22/scratch/broot/miniconda/envs/py3k/lib/python3.6/site-packages (from catutils==0.15.dev1) Requirement already satisfied: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) (0.16.dev1) req: nose comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: numpy comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: matplotlib<2.2.0 comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: Shapely comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: GDAL comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: pyyaml comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: jinja2 comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: scripttest comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: netCDF4 comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: six comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) req: atomic_context@ git+ssh://git@***********.com/common/atomic_context.git@release comes_from: aershp>=0.10 in /nas/home/broot/Programs/tools/aershp/lib (from catutils==0.15.dev1) Exception: Traceback (most recent call last): File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 143, in main status = self.run(options, args) File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 318, in run resolver.resolve(requirement_set) File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/resolve.py", line 102, in resolve self._resolve_one(requirement_set, req) File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/resolve.py", line 318, in _resolve_one add_req(subreq, extras_requested=available_requested) File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/resolve.py", line 275, in add_req wheel_cache=self.wheel_cache, File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/req/constructors.py", line 290, in install_req_from_req if req.url and comes_from.link.netloc in domains_not_allowed: AttributeError: 'NoneType' object has no attribute 'netloc' ``` A bit of explanation of my dependency tree. I am installing a package called "catutils". It has a dependency on another private package called "aershp". That package, in turn, has a dependency upon two other private, pure-python, packages called "ncxml" and "atomic_context". I installed "aershp" via "pip install -e .", and it fetched the other two packages from our gitlab server. This failure happened when I tried doing "pip install -e ." for the catutils package. Some additional insights. I have gone back and reinstalled (`pip install -e .`) the "atomic_context" and the "ncxml" packages. I then `pip uninstall aershp`, and then did `pip install -e .`. This failed for some odd reason: ``` Could not find a version that satisfies the requirement aershp>=0.10 (from catutils==0.15.dev1) (from versions: )``` So, I then did a `pip uninstall catutils`: which said that it was skipping it because it is not installed (as expected), but then went back to the "aershp" package and redid `pip install -e .`, and instead of the unsatisfiable error, I got the same error as originally posted above.
Correction, when I reinstalled "aershp" after fake-uninstalling "catutils", it installed fine, but installing "catutils" still failed. It looks like the line causing the exception was introduced in PR #5571. This should be fixed in #5788, there's a test in this comment: https://github.com/pypa/pip/pull/5788#issuecomment-427596606. Yeah, looking at that comment, it seems to make sense (although, my knowledge of pip internals is extremely limited). Any thoughts on the incomplete cleanup from the failed install? @benoit-pierre -- your fixes for this bug (which has bitten me) look good. But the PRs are now closed. Did you find a way around this issue? I also seem to have the same problem: - pip 19.0.3 - OS Windows 10 (using git bash) - python 3.6 My situation seems analogous to the situation reported here. I am installing a private package called deep-nlp-embedding (`pip install -e .`) that depends on another private package called deep-nlp-core that was previously installed with `pip install -e .` ``` $ pip install -e . Obtaining file:///E:/Repos/flamingo-nlp/deep-nlp-embedding Requirement already satisfied: deep-nlp-core in e:\repos\flamingo-nlp\deep-nlp-core (from deep-nlp-embedding==0.0.2) (0.0.2) Exception: Traceback (most recent call last): File "C:\Anaconda\envs\flamingo_nlp\lib\site-packages\pip\_internal\cli\base_command.py", line 179, in main status = self.run(options, args) File "C:\Anaconda\envs\flamingo_nlp\lib\site-packages\pip\_internal\commands\install.py", line 315, in run resolver.resolve(requirement_set) File "C:\Anaconda\envs\flamingo_nlp\lib\site-packages\pip\_internal\resolve.py", line 131, in resolve self._resolve_one(requirement_set, req) File "C:\Anaconda\envs\flamingo_nlp\lib\site-packages\pip\_internal\resolve.py", line 357, in _resolve_one add_req(subreq, extras_requested=available_requested) File "C:\Anaconda\envs\flamingo_nlp\lib\site-packages\pip\_internal\resolve.py", line 314, in add_req use_pep517=self.use_pep517 File "C:\Anaconda\envs\flamingo_nlp\lib\site-packages\pip\_internal\req\constructors.py", line 328, in install_req_from_req_string if req.url and comes_from.link.netloc in domains_not_allowed: AttributeError: 'NoneType' object has no attribute 'netloc' ``` Note the first private package was installed using [PEP 508 URLS](https://www.python.org/dev/peps/pep-0508/), specfically: ``` torch@ https://download.pytorch.org/whl/cu90/torch-1.0.0-cp36-cp36m-win_amd64.whl from https://download.pytorch.org/whl/cu90/torch-1.0.0-cp36-cp36m-win_amd64.whl in c:\anaconda\envs\flamingo_nlp\lib\site-packages (from deep-nlp-core==0.0.2) (1.0.0) ```
2019-03-14T17:54:21Z
[]
[]
Traceback (most recent call last): File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 143, in main status = self.run(options, args) File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 318, in run resolver.resolve(requirement_set) File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/resolve.py", line 102, in resolve self._resolve_one(requirement_set, req) File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/resolve.py", line 318, in _resolve_one add_req(subreq, extras_requested=available_requested) File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/resolve.py", line 275, in add_req wheel_cache=self.wheel_cache, File "/home/broot/scratch/miniconda/envs/py3k/lib/python3.6/site-packages/pip/_internal/req/constructors.py", line 290, in install_req_from_req if req.url and comes_from.link.netloc in domains_not_allowed: AttributeError: 'NoneType' object has no attribute 'netloc'
17,460
pypa/pip
pypa__pip-6542
f44344f1220bce5cd942641f832cb407ed477f06
diff --git a/src/pip/_internal/exceptions.py b/src/pip/_internal/exceptions.py --- a/src/pip/_internal/exceptions.py +++ b/src/pip/_internal/exceptions.py @@ -9,6 +9,7 @@ if MYPY_CHECK_RUNNING: from typing import Optional + from pip._vendor.pkg_resources import Distribution from pip._internal.req.req_install import InstallRequirement @@ -28,6 +29,36 @@ class UninstallationError(PipError): """General exception during uninstallation""" +class NoneMetadataError(PipError): + """ + Raised when accessing "METADATA" or "PKG-INFO" metadata for a + pip._vendor.pkg_resources.Distribution object and + `dist.has_metadata('METADATA')` returns True but + `dist.get_metadata('METADATA')` returns None (and similarly for + "PKG-INFO"). + """ + + def __init__(self, dist, metadata_name): + # type: (Distribution, str) -> None + """ + :param dist: A Distribution object. + :param metadata_name: The name of the metadata being accessed + (can be "METADATA" or "PKG-INFO"). + """ + self.dist = dist + self.metadata_name = metadata_name + + def __str__(self): + # type: () -> str + # Use `dist` in the error message because its stringification + # includes more information, like the version and location. + return ( + 'None {} metadata found for distribution: {}'.format( + self.metadata_name, self.dist, + ) + ) + + class DistributionNotFound(InstallationError): """Raised when a distribution cannot be found to satisfy a requirement""" diff --git a/src/pip/_internal/utils/packaging.py b/src/pip/_internal/utils/packaging.py --- a/src/pip/_internal/utils/packaging.py +++ b/src/pip/_internal/utils/packaging.py @@ -6,6 +6,7 @@ from pip._vendor import pkg_resources from pip._vendor.packaging import specifiers, version +from pip._internal.exceptions import NoneMetadataError from pip._internal.utils.misc import display_path from pip._internal.utils.typing import MYPY_CHECK_RUNNING @@ -43,16 +44,27 @@ def check_requires_python(requires_python, version_info): def get_metadata(dist): # type: (Distribution) -> Message + """ + :raises NoneMetadataError: if the distribution reports `has_metadata()` + True but `get_metadata()` returns None. + """ + metadata_name = 'METADATA' if (isinstance(dist, pkg_resources.DistInfoDistribution) and - dist.has_metadata('METADATA')): - metadata = dist.get_metadata('METADATA') + dist.has_metadata(metadata_name)): + metadata = dist.get_metadata(metadata_name) elif dist.has_metadata('PKG-INFO'): - metadata = dist.get_metadata('PKG-INFO') + metadata_name = 'PKG-INFO' + metadata = dist.get_metadata(metadata_name) else: logger.warning("No metadata found in %s", display_path(dist.location)) metadata = '' + if metadata is None: + raise NoneMetadataError(dist, metadata_name) + feed_parser = FeedParser() + # The following line errors out if with a "NoneType" TypeError if + # passed metadata=None. feed_parser.feed(metadata) return feed_parser.close()
Cryptic error when a dependency's PKG_INFO/METADATA is missing * Pip version: 9.0.1 * Python version: 3.6.4 * Operating system: Ubuntu 17.10 ### Description: Pip crashes with a cryptic error when it doesn't find a dependency's package metadata. ### What I've run: A certain dependency was installed using `conda` and was lacking a `PKG-INFO` file in the egg-info. When installing the desired package, pip fails right after processing the dependency with this error traceback: ``` Exception: Traceback (most recent call last): File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/wheel.py", line 756, in build self.requirement_set.prepare_files(self.finder) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 666, in _prepare_file check_dist_requires_python(dist) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/utils/packaging.py", line 48, in check_dist_requires_python feed_parser.feed(metadata) File "/home/nezar/miniconda3/lib/python3.6/email/feedparser.py", line 175, in feed self._input.push(data) File "/home/nezar/miniconda3/lib/python3.6/email/feedparser.py", line 103, in push self._partial.write(data) TypeError: string argument expected, got 'NoneType' ``` On inspecting `pip/utils/packaging.py`: ```python def get_metadata(dist): if (isinstance(dist, pkg_resources.DistInfoDistribution) and dist.has_metadata('METADATA')): return dist.get_metadata('METADATA') elif dist.has_metadata('PKG-INFO'): return dist.get_metadata('PKG-INFO') def check_dist_requires_python(dist): metadata = get_metadata(dist) feed_parser = FeedParser() feed_parser.feed(metadata) pkg_info_dict = feed_parser.close() requires_python = pkg_info_dict.get('Requires-Python') try: if not check_requires_python(requires_python): raise exceptions.UnsupportedPythonVersion( "%s requires Python '%s' but the running Python is %s" % ( dist.project_name, requires_python, '.'.join(map(str, sys.version_info[:3])),) ) except specifiers.InvalidSpecifier as e: logger.warning( "Package %s has an invalid Requires-Python entry %s - %s" % ( dist.project_name, requires_python, e)) return ``` `get_metadata` is returning None when it doesn't find anything, which causes `feed_parser` to crash.
@cytolentino Hi! Could you take a look at this issue? There should probably be a conditional somewhere, that prevents us from passing `None` to `feed_parser`, aborting early. :) Hi @pradyunsg! I've just had a look at this and it seems like someone else has already fixed this (see [here](https://github.com/pypa/pip/blob/master/src/pip/_internal/utils/packaging.py#L42-L44)). That said, I've added in a regression test for this case to confirm that it's fixed over here: PR https://github.com/pypa/pip/pull/6003 :) Marking this as a bug because pip shouldn't necessarily be crashing here (at least sometimes I don't think).
2019-05-26T19:31:04Z
[]
[]
Traceback (most recent call last): File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/wheel.py", line 756, in build self.requirement_set.prepare_files(self.finder) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 666, in _prepare_file check_dist_requires_python(dist) File "/home/nezar/miniconda3/lib/python3.6/site-packages/pip/utils/packaging.py", line 48, in check_dist_requires_python feed_parser.feed(metadata) File "/home/nezar/miniconda3/lib/python3.6/email/feedparser.py", line 175, in feed self._input.push(data) File "/home/nezar/miniconda3/lib/python3.6/email/feedparser.py", line 103, in push self._partial.write(data) TypeError: string argument expected, got 'NoneType'
17,472
pypa/pip
pypa__pip-6577
107258da0b23acf44c18377387a1d4b21657ef8d
diff --git a/src/pip/_internal/commands/download.py b/src/pip/_internal/commands/download.py --- a/src/pip/_internal/commands/download.py +++ b/src/pip/_internal/commands/download.py @@ -152,6 +152,7 @@ def run(self, options, args): upgrade_strategy="to-satisfy-only", force_reinstall=False, ignore_dependencies=options.ignore_dependencies, + py_version_info=options.python_version, ignore_requires_python=False, ignore_installed=True, isolated=options.isolated_mode, diff --git a/src/pip/_internal/index.py b/src/pip/_internal/index.py --- a/src/pip/_internal/index.py +++ b/src/pip/_internal/index.py @@ -34,7 +34,7 @@ from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( ARCHIVE_EXTENSIONS, SUPPORTED_EXTENSIONS, WHEEL_EXTENSION, normalize_path, - path_to_url, redact_password_from_url, + normalize_version_info, path_to_url, redact_password_from_url, ) from pip._internal.utils.packaging import check_requires_python from pip._internal.utils.typing import MYPY_CHECK_RUNNING @@ -258,7 +258,7 @@ def _get_html_page(link, session=None): def _check_link_requires_python( link, # type: Link - version_info, # type: Tuple[int, ...] + version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool ): # type: (...) -> bool @@ -266,8 +266,8 @@ def _check_link_requires_python( Return whether the given Python version is compatible with a link's "Requires-Python" value. - :param version_info: The Python version to use to check, as a 3-tuple - of ints (major-minor-micro). + :param version_info: A 3-tuple of ints representing the Python + major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. """ @@ -311,16 +311,17 @@ def __init__( valid_tags, # type: List[Pep425Tag] prefer_binary=False, # type: bool allow_all_prereleases=False, # type: bool - py_version_info=None, # type: Optional[Tuple[int, ...]] + py_version_info=None, # type: Optional[Tuple[int, int, int]] ignore_requires_python=None, # type: Optional[bool] ): # type: (...) -> None """ :param allow_all_prereleases: Whether to allow all pre-releases. - :param py_version_info: The Python version, as a 3-tuple of ints - representing a major-minor-micro version, to use to check both - the Python version embedded in the filename and the package's - "Requires-Python" metadata. Defaults to `sys.version_info[:3]`. + :param py_version_info: A 3-tuple of ints representing the Python + major-minor-micro version to use to check both the Python version + embedded in the filename and the package's "Requires-Python" + metadata. If None (the default), then `sys.version_info[:3]` + will be used. :param ignore_requires_python: Whether to ignore incompatible "Requires-Python" values in links. Defaults to False. """ @@ -666,6 +667,8 @@ def create( else: versions = None + py_version_info = normalize_version_info(py_version_info) + # The valid tags to check potential found wheel candidates against valid_tags = get_supported( versions=versions, @@ -676,6 +679,7 @@ def create( candidate_evaluator = CandidateEvaluator( valid_tags=valid_tags, prefer_binary=prefer_binary, allow_all_prereleases=allow_all_prereleases, + py_version_info=py_version_info, ignore_requires_python=ignore_requires_python, ) diff --git a/src/pip/_internal/legacy_resolve.py b/src/pip/_internal/legacy_resolve.py --- a/src/pip/_internal/legacy_resolve.py +++ b/src/pip/_internal/legacy_resolve.py @@ -23,7 +23,9 @@ ) from pip._internal.req.constructors import install_req_from_req_string from pip._internal.utils.logging import indent_log -from pip._internal.utils.misc import dist_in_usersite, ensure_dir +from pip._internal.utils.misc import ( + dist_in_usersite, ensure_dir, normalize_version_info, +) from pip._internal.utils.packaging import ( check_requires_python, get_requires_python, ) @@ -46,7 +48,7 @@ def _check_dist_requires_python( dist, # type: pkg_resources.Distribution - version_info, # type: Tuple[int, ...] + version_info, # type: Tuple[int, int, int] ignore_requires_python=False, # type: bool ): # type: (...) -> None @@ -54,8 +56,8 @@ def _check_dist_requires_python( Check whether the given Python version is compatible with a distribution's "Requires-Python" value. - :param version_info: The Python version to use to check, as a 3-tuple - of ints (major-minor-micro). + :param version_info: A 3-tuple of ints representing the Python + major-minor-micro version to check. :param ignore_requires_python: Whether to ignore the "Requires-Python" value if the given Python version isn't compatible. @@ -121,6 +123,8 @@ def __init__( if py_version_info is None: py_version_info = sys.version_info[:3] + else: + py_version_info = normalize_version_info(py_version_info) self._py_version_info = py_version_info diff --git a/src/pip/_internal/utils/misc.py b/src/pip/_internal/utils/misc.py --- a/src/pip/_internal/utils/misc.py +++ b/src/pip/_internal/utils/misc.py @@ -45,13 +45,23 @@ if MYPY_CHECK_RUNNING: from typing import ( - Optional, Tuple, Iterable, List, Match, Union, Any, Mapping, Text, - AnyStr, Container + Any, AnyStr, Container, Iterable, List, Mapping, Match, Optional, Text, + Union, ) from pip._vendor.pkg_resources import Distribution from pip._internal.models.link import Link from pip._internal.utils.ui import SpinnerInterface +try: + from typing import cast, Tuple + VersionInfo = Tuple[int, int, int] +except ImportError: + # typing's cast() isn't supported in code comments, so we need to + # define a dummy, no-op version. + def cast(typ, val): + return val + VersionInfo = None + __all__ = ['rmtree', 'display_path', 'backup_dir', 'ask', 'splitext', @@ -94,6 +104,29 @@ logger.debug('lzma module is not available') +def normalize_version_info(py_version_info): + # type: (Optional[Tuple[int, ...]]) -> Optional[Tuple[int, int, int]] + """ + Convert a tuple of ints representing a Python version to one of length + three. + + :param py_version_info: a tuple of ints representing a Python version, + or None to specify no version. The tuple can have any length. + + :return: a tuple of length three if `py_version_info` is non-None. + Otherwise, return `py_version_info` unchanged (i.e. None). + """ + if py_version_info is None: + return None + + if len(py_version_info) < 3: + py_version_info += (3 - len(py_version_info)) * (0,) + elif len(py_version_info) > 3: + py_version_info = py_version_info[:3] + + return cast(VersionInfo, py_version_info) + + def ensure_dir(path): # type: (AnyStr) -> None """os.path.makedirs without EEXIST.""" diff --git a/src/pip/_internal/utils/packaging.py b/src/pip/_internal/utils/packaging.py --- a/src/pip/_internal/utils/packaging.py +++ b/src/pip/_internal/utils/packaging.py @@ -22,16 +22,15 @@ def check_requires_python(requires_python, version_info): # type: (Optional[str], Tuple[int, ...]) -> bool """ - Check if the given Python version matches a `requires_python` specifier. + Check if the given Python version matches a "Requires-Python" specifier. - :param version_info: A 3-tuple of ints representing the Python + :param version_info: A 3-tuple of ints representing a Python major-minor-micro version to check (e.g. `sys.version_info[:3]`). - Returns `True` if the version of python in use matches the requirement. - Returns `False` if the version of python in use does not matches the - requirement. + :return: `True` if the given Python version satisfies the requirement. + Otherwise, return `False`. - Raises an InvalidSpecifier if `requires_python` have an invalid format. + :raises InvalidSpecifier: If `requires_python` has an invalid format. """ if requires_python is None: # The package provides no information
`pip download --python-version` fails when downloaded package doesn't support the Python version running pip * Pip version: 10.0.1 * Python version: 2.7 * Operating system: Linux (Debian) ### Description: I'm using `pip download` to download packages for a different version of Python than the version that pip is running on. Specifically, I'm using pip on Python 2.7 to download packages for Python 3.5. The wheel for Python 3.5 is downloaded successfully, but `pip download` exits with an error since the wheel specifies a minimum Python version of 3.4. Setting `ignore_requires_python=True` in `pip/_internal/commands/download.py` turns the error into a warning (which still isn't ideal), but would the proper fix be for `check_requires_python` to consider the Python version passed to the `download` command? ### What I've run: ``` $ pip download python-rapidjson --dest . --no-deps --platform manylinux1_x86_64 --python-version 35 --implementation cp --abi cp35m Collecting python-rapidjson File was already downloaded /tmp/py/python_rapidjson-0.5.2-cp35-cp35m-manylinux1_x86_64.whl python-rapidjson requires Python '>=3.4' but the running Python is 2.7.9 ``` With verbose output, the last part of the output is: ``` Downloading from URL https://files.pythonhosted.org/packages/44/59/70b5060b7a5afaec36cdb618dd1c59a389642e739a49b76fef81446f18f8/python_rapidjson-0.5.2-cp35-cp35m-manylinux1_x86_64.whl#sha256=d20ca8dfd9db296941c1f978231ddf9402494c868ae8d6e431b59c8406063cad (from https://pypi.org/simple/python-rapidjson/) Saved ./python_rapidjson-0.5.2-cp35-cp35m-manylinux1_x86_64.whl python-rapidjson requires Python '>=3.4' but the running Python is 2.7.9 Exception information: Traceback (most recent call last): File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/commands/download.py", line 221, in run resolver.resolve(requirement_set) File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/resolve.py", line 103, in resolve self._resolve_one(requirement_set, req) File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/resolve.py", line 262, in _resolve_one check_dist_requires_python(dist) File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/utils/packaging.py", line 55, in check_dist_requires_python '.'.join(map(str, sys.version_info[:3])),) UnsupportedPythonVersion: python-rapidjson requires Python '>=3.4' but the running Python is 2.7.9 ```
I'm personally not sure what's supposed to happen here. I'm not familiar with Python-Requires behaviors. Maybe someone else from @pypa/pip-committers is. I was surprised by this behaviour as well. I'm trying to use "pip download" to gather required packages for deployment elsewhere, and this makes it extremely difficult to do so. It's odd that "pip download" is inconsistent here -- it pays attention to python version in the PackageFinder, but not here. I'd say this is a valid bug: pip should not check `Python-Requires` in this case. I posted PR https://github.com/pypa/pip/pull/6528, which will help with this issue.
2019-06-06T08:34:16Z
[]
[]
Traceback (most recent call last): File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/basecommand.py", line 228, in main status = self.run(options, args) File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/commands/download.py", line 221, in run resolver.resolve(requirement_set) File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/resolve.py", line 103, in resolve self._resolve_one(requirement_set, req) File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/resolve.py", line 262, in _resolve_one check_dist_requires_python(dist) File "/home/michael/apps/virtualenv/local/lib/python2.7/site-packages/pip/_internal/utils/packaging.py", line 55, in check_dist_requires_python '.'.join(map(str, sys.version_info[:3])),) UnsupportedPythonVersion: python-rapidjson requires Python '>=3.4' but the running Python is 2.7.9
17,474
pypa/pip
pypa__pip-6774
369ec7c0a8a81a076ca5584c34c8530d7a30a220
diff --git a/src/pip/_internal/models/link.py b/src/pip/_internal/models/link.py --- a/src/pip/_internal/models/link.py +++ b/src/pip/_internal/models/link.py @@ -200,11 +200,11 @@ def has_hash(self): return self.hash_name is not None def is_hash_allowed(self, hashes): - # type: (Hashes) -> bool + # type: (Optional[Hashes]) -> bool """ Return True if the link has a hash and it is allowed. """ - if not self.has_hash: + if hashes is None or not self.has_hash: return False # Assert non-None so mypy knows self.hash_name and self.hash are str. assert self.hash_name is not None
AttributeError: 'NoneType' object has no attribute 'is_hash_allowed' **Environment** * pip version: 19.2 * Python version: 3.6.8 * OS: Mac OSX (Darwin Kernel Version 18.6.0) **Description** I made env update in my project including pip as well. After that I wanted to check outdated packages with command: ```python pip list --outdated --format=columns ``` After that exception was raised. **Expected behavior** I expected list of packages or empty list. **How to Reproduce** 1. Get the newest version of package from PyPI. 2. Then run `pip list --outdated --format=columns` 3. An error occurs. **Output** ```python (env) project (develop) $ pip list --outdated --format=columns ERROR: Exception: Traceback (most recent call last): File "/project/env/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 188, in main status = self.run(options, args) File "/project/env/lib/python3.6/site-packages/pip/_internal/commands/list.py", line 156, in run packages = self.get_outdated(packages, options) File "/project/env/lib/python3.6/site-packages/pip/_internal/commands/list.py", line 164, in get_outdated dist for dist in self.iter_packages_latest_infos(packages, options) File "/project/env/lib/python3.6/site-packages/pip/_internal/commands/list.py", line 164, in <listcomp> dist for dist in self.iter_packages_latest_infos(packages, options) File "/project/env/lib/python3.6/site-packages/pip/_internal/commands/list.py", line 195, in iter_packages_latest_infos best_candidate = evaluator.get_best_candidate(all_candidates) File "/project/env/lib/python3.6/site-packages/pip/_internal/index.py", line 729, in get_best_candidate best_candidate = max(candidates, key=self._sort_key) File "/project/env/lib/python3.6/site-packages/pip/_internal/index.py", line 710, in _sort_key has_allowed_hash = int(link.is_hash_allowed(self._hashes)) File "/project/env/lib/python3.6/site-packages/pip/_internal/models/link.py", line 213, in is_hash_allowed return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash) AttributeError: 'NoneType' object has no attribute 'is_hash_allowed' ```
@ptynecki Thanks for filing this issue! /cc @cjerdonek since he's worked on this part of the codebase and is more familiar with it than me. Same issue on Windows 10, Python 3.7.3 Same issue on Ubuntu 18.04.2 LTS, Python 3.6.8 Same issue on macOS 18.6.0 and Python 3.7.4 Same issue on Windows 10, Python 3.7.4 Same issue on Fedora 29, Python 3.7.3. For now, as a workaround, ... ```bash python3 -m pip install -UI --user 'pip<19.2' ``` reinstalled `pip` version 19.1.1. Although, the complete command output is curious. ```bash $ python3 -m pip install -UI --user 'pip<19.2' Collecting pip<19.2 Using cached https://files.pythonhosted.org/packages/5c/e0/be401c003291b56efc55aeba6a80ab790d3d4cece2778288d65323009420/pip-19.1.1-py2.py3-none-any.whl Installing collected packages: pip Successfully installed pip-19.2 ``` Why does it report `Successfully installed pip-19.2`? Thanks for the confirmation of this occurring on multiple OSes! Folks, if you're facing the same issue, please don't post additional comments. Please use GitHub reactions to upvote the first post and subscribe to the issue. That way the maintainers would be able to have a discussion on how to resolve this in this issue -- additional "me too" comments won't help anyone. Hmm, I guess the type checker failed us here. The type annotation says `hashes` must be non-None, but it is None in the reported cases: https://github.com/pypa/pip/blob/369ec7c0a8a81a076ca5584c34c8530d7a30a220/src/pip/_internal/models/link.py#L202-L209 After a quick look, I think a good fix for now may be to update `Link.is_hash_allowed(hashes)` to return `False` if `hashes` is None (and bring the annotation into alignment by updating the parameter to `Optional[Hashes]`). That's probably simpler and more sure-fire at this point than trying to update things in possibly multiple places to ensure that the `hashes` argument is always non-`None`, especially since we can't seem to lean on the type checker to confirm with 100% certainty. > I guess the type checker failed us here. Ahhh. Yep -- strict_optional is False for `pip._internal.index` and this is exactly that failure. > we can't seem to lean on the type checker to confirm with 100% certainty. Yea, we can't completely rely on it, as long as we have these flags for incremental adoption. > Ahhh. Yep -- strict_optional is False for pip._internal.index and this is exactly that failure. And even though `models/link.py` where the function is defined does have `strict_optional` enabled.
2019-07-23T09:20:37Z
[]
[]
Traceback (most recent call last): File "/project/env/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 188, in main status = self.run(options, args) File "/project/env/lib/python3.6/site-packages/pip/_internal/commands/list.py", line 156, in run packages = self.get_outdated(packages, options) File "/project/env/lib/python3.6/site-packages/pip/_internal/commands/list.py", line 164, in get_outdated dist for dist in self.iter_packages_latest_infos(packages, options) File "/project/env/lib/python3.6/site-packages/pip/_internal/commands/list.py", line 164, in <listcomp> dist for dist in self.iter_packages_latest_infos(packages, options) File "/project/env/lib/python3.6/site-packages/pip/_internal/commands/list.py", line 195, in iter_packages_latest_infos best_candidate = evaluator.get_best_candidate(all_candidates) File "/project/env/lib/python3.6/site-packages/pip/_internal/index.py", line 729, in get_best_candidate best_candidate = max(candidates, key=self._sort_key) File "/project/env/lib/python3.6/site-packages/pip/_internal/index.py", line 710, in _sort_key has_allowed_hash = int(link.is_hash_allowed(self._hashes)) File "/project/env/lib/python3.6/site-packages/pip/_internal/models/link.py", line 213, in is_hash_allowed return hashes.is_hash_allowed(self.hash_name, hex_digest=self.hash) AttributeError: 'NoneType' object has no attribute 'is_hash_allowed'
17,491
pypa/pip
pypa__pip-7118
7dc7b81675027eee69c804af20f3ab952959f3d8
diff --git a/src/pip/_internal/utils/misc.py b/src/pip/_internal/utils/misc.py --- a/src/pip/_internal/utils/misc.py +++ b/src/pip/_internal/utils/misc.py @@ -864,3 +864,10 @@ def protect_pip_from_modification_on_windows(modifying_pip): 'To modify pip, please run the following command:\n{}' .format(" ".join(new_command)) ) + + +def is_console_interactive(): + # type: () -> bool + """Is this console interactive? + """ + return sys.stdin is not None and sys.stdin.isatty() diff --git a/src/pip/_internal/vcs/subversion.py b/src/pip/_internal/vcs/subversion.py --- a/src/pip/_internal/vcs/subversion.py +++ b/src/pip/_internal/vcs/subversion.py @@ -6,11 +6,11 @@ import logging import os import re -import sys from pip._internal.utils.logging import indent_log from pip._internal.utils.misc import ( display_path, + is_console_interactive, rmtree, split_auth_from_netloc, ) @@ -188,7 +188,7 @@ def is_commit_id_equal(cls, dest, name): def __init__(self, use_interactive=None): # type: (bool) -> None if use_interactive is None: - use_interactive = sys.stdin.isatty() + use_interactive = is_console_interactive() self.use_interactive = use_interactive # This member is used to cache the fetched version of the current
crash when `sys.stdin` is `None` in subversion.py **Environment** * pip version: 19.2.3 * Python version: 3.7.4 * OS: archlinux **Description** The code that determines if to use interactive mode in [subversion.py](https://github.com/pypa/pip/blob/master/src/pip/_internal/vcs/subversion.py#L191) breaks when `sys.stdin` is `None` **Expected behavior** Does not crash. **How to Reproduce** (On linux) 1. Run: `virtualenv -p python3 env` 1. Run: `source env/bin/activate` 1. Run: `python -c 'import pip._internal as pip' 0<&-` (this simulates a `None` `sys.stdin`) **Output** ``` $ virtualenv -p python3 env Running virtualenv with interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /tmp/env/bin/python3 Also creating executable in /tmp/env/bin/python Installing setuptools, pip, wheel... done. $ source env/bin/activate (env) $ python -c 'import pip._internal as pip' 0<&- Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/env/lib/python3.7/site-packages/pip/_internal/__init__.py", line 40, in <module> from pip._internal.cli.autocompletion import autocomplete File "/tmp/env/lib/python3.7/site-packages/pip/_internal/cli/autocompletion.py", line 8, in <module> from pip._internal.cli.main_parser import create_main_parser File "/tmp/env/lib/python3.7/site-packages/pip/_internal/cli/main_parser.py", line 11, in <module> from pip._internal.commands import ( File "/tmp/env/lib/python3.7/site-packages/pip/_internal/commands/__init__.py", line 6, in <module> from pip._internal.commands.completion import CompletionCommand File "/tmp/env/lib/python3.7/site-packages/pip/_internal/commands/completion.py", line 6, in <module> from pip._internal.cli.base_command import Command File "/tmp/env/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 21, in <module> from pip._internal.download import PipSession File "/tmp/env/lib/python3.7/site-packages/pip/_internal/download.py", line 47, in <module> from pip._internal.vcs import vcs File "/tmp/env/lib/python3.7/site-packages/pip/_internal/vcs/__init__.py", line 12, in <module> import pip._internal.vcs.subversion # noqa: F401 File "/tmp/env/lib/python3.7/site-packages/pip/_internal/vcs/subversion.py", line 314, in <module> vcs.register(Subversion) File "/tmp/env/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py", line 165, in register self._registry[cls.name] = cls() File "/tmp/env/lib/python3.7/site-packages/pip/_internal/vcs/subversion.py", line 180, in __init__ use_interactive = sys.stdin.isatty() AttributeError: 'NoneType' object has no attribute 'isatty' (env) $ ``` **Notes** And in case you're wondering how I got to this internal API: I'm running (on AWS Lambda) [awslimitchecker](https://github.com/jantman/awslimitchecker), which uses [versionfinder](https://github.com/jantman/versionfinder), which [uses pip](https://github.com/jantman/versionfinder/blob/master/versionfinder/versionfinder.py#L48)
2019-09-30T13:27:25Z
[]
[]
Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/env/lib/python3.7/site-packages/pip/_internal/__init__.py", line 40, in <module> from pip._internal.cli.autocompletion import autocomplete File "/tmp/env/lib/python3.7/site-packages/pip/_internal/cli/autocompletion.py", line 8, in <module> from pip._internal.cli.main_parser import create_main_parser File "/tmp/env/lib/python3.7/site-packages/pip/_internal/cli/main_parser.py", line 11, in <module> from pip._internal.commands import ( File "/tmp/env/lib/python3.7/site-packages/pip/_internal/commands/__init__.py", line 6, in <module> from pip._internal.commands.completion import CompletionCommand File "/tmp/env/lib/python3.7/site-packages/pip/_internal/commands/completion.py", line 6, in <module> from pip._internal.cli.base_command import Command File "/tmp/env/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 21, in <module> from pip._internal.download import PipSession File "/tmp/env/lib/python3.7/site-packages/pip/_internal/download.py", line 47, in <module> from pip._internal.vcs import vcs File "/tmp/env/lib/python3.7/site-packages/pip/_internal/vcs/__init__.py", line 12, in <module> import pip._internal.vcs.subversion # noqa: F401 File "/tmp/env/lib/python3.7/site-packages/pip/_internal/vcs/subversion.py", line 314, in <module> vcs.register(Subversion) File "/tmp/env/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py", line 165, in register self._registry[cls.name] = cls() File "/tmp/env/lib/python3.7/site-packages/pip/_internal/vcs/subversion.py", line 180, in __init__ use_interactive = sys.stdin.isatty() AttributeError: 'NoneType' object has no attribute 'isatty'
17,514
pypa/pip
pypa__pip-7494
c06874c471503f3e3f9931f1f21665b932da5994
diff --git a/src/pip/_internal/operations/install/wheel.py b/src/pip/_internal/operations/install/wheel.py --- a/src/pip/_internal/operations/install/wheel.py +++ b/src/pip/_internal/operations/install/wheel.py @@ -315,8 +315,10 @@ def install_unpacked_wheel( :param pycompile: Whether to byte-compile installed Python files :param warn_script_location: Whether to check that scripts are installed into a directory on PATH - :raises UnsupportedWheel: when the directory holds an unpacked wheel with - incompatible Wheel-Version + :raises UnsupportedWheel: + * when the directory holds an unpacked wheel with incompatible + Wheel-Version + * when the .dist-info dir does not match the wheel """ # TODO: Investigate and break this up. # TODO: Look into moving this into a dedicated class for representing an @@ -381,8 +383,7 @@ def clobber( continue elif ( is_base and - s.endswith('.dist-info') and - canonicalize_name(s).startswith(canonicalize_name(name)) + s.endswith('.dist-info') ): assert not info_dir, ( 'Multiple .dist-info directories: {}, '.format( @@ -445,6 +446,15 @@ def clobber( req_description ) + info_dir_name = canonicalize_name(os.path.basename(info_dir[0])) + canonical_name = canonicalize_name(name) + if not info_dir_name.startswith(canonical_name): + raise UnsupportedWheel( + "{} .dist-info directory {!r} does not start with {!r}".format( + req_description, os.path.basename(info_dir[0]), canonical_name + ) + ) + # Get the defined entry points ep_file = os.path.join(info_dir[0], 'entry_points.txt') console, gui = get_entrypoints(ep_file)
pip sometimes prohibits 2 .dist-info directories in wheels **Environment** * pip version: 19.3.1 * Python version: 3.8.0 * OS: Linux **Description** Currently, pip rejects wheel files containing multiple `.dist-info` directories, but only if they start with the name of the package being installed. **Expected behavior** pip should prohibit more than 1 top-level `.dist-info` directory, without regard to the name of the directories (besides ending with `.dist-info`). From [PEP 427](https://www.python.org/dev/peps/pep-0427/#abstract): > A wheel is a ZIP-format archive with a specially formatted file name and the `.whl` extension. It contains a **single** distribution And from [PEP 376](https://www.python.org/dev/peps/pep-0376/#one-dist-info-directory-per-installed-distribution): > One .dist-info directory per installed distribution **How to Reproduce** Save `t.sh` below, make it executable, and execute it. <details> <summary>t.sh</summary> ``` #!/bin/sh cd "$(mktemp -d)" python -m venv env . env/bin/activate pip install --upgrade pip wheel echo "= Versions =====================================================================" python -V pip -V wheel version echo "= Setup ========================================================================" echo "from setuptools import setup; setup(name='hello')" > setup.py echo "= (1) Base case ================================================================" echo "= (1) Build ====================================================================" python setup.py bdist_wheel echo "= (1) Install ==================================================================" pip install --ignore-installed dist/hello-0.0.0-py3-none-any.whl echo "= (2) 2 .dist-info dirs (expected) =============================================" echo "= (2) Build ====================================================================" python setup.py bdist_wheel echo "= (2) Add second .dist-info (shared prefix) ====================================" mkdir hello-example-0.0.0.dist-info zip dist/hello-0.0.0-py3-none-any.whl hello-example-0.0.0.dist-info echo "= (2) Install ==================================================================" pip install --ignore-installed dist/hello-0.0.0-py3-none-any.whl echo "= (3) 2 .dist-info dirs (NOT expected) =========================================" echo "= (3) Build ====================================================================" python setup.py bdist_wheel echo "= (3) Add second .dist-info (no shared prefix) =================================" mkdir goodbye-example-0.0.0.dist-info zip dist/hello-0.0.0-py3-none-any.whl goodbye-example-0.0.0.dist-info echo "= (3) Install ==================================================================" pip install --ignore-installed dist/hello-0.0.0-py3-none-any.whl ``` </details> **Output** <details> <summary>Output</summary> ``` Collecting pip Using cached https://files.pythonhosted.org/packages/00/b6/9cfa56b4081ad13874b0c6f96af8ce16cfbc1cb06bedf8e9164ce5551ec1/pip-19.3.1-py2.py3-none-any.whl Collecting wheel Using cached https://files.pythonhosted.org/packages/00/83/b4a77d044e78ad1a45610eb88f745be2fd2c6d658f9798a15e384b7d57c9/wheel-0.33.6-py2.py3-none-any.whl Installing collected packages: pip, wheel Found existing installation: pip 19.2.3 Uninstalling pip-19.2.3: Successfully uninstalled pip-19.2.3 Successfully installed pip-19.3.1 wheel-0.33.6 = Versions ===================================================================== Python 3.8.0 pip 19.3.1 from /tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip (python 3.8) wheel 0.33.6 = Setup ======================================================================== = (1) Base case ================================================================ = (1) Build ==================================================================== running bdist_wheel running build installing to build/bdist.linux-x86_64/wheel running install running install_egg_info running egg_info creating hello.egg-info writing hello.egg-info/PKG-INFO writing dependency_links to hello.egg-info/dependency_links.txt writing top-level names to hello.egg-info/top_level.txt writing manifest file 'hello.egg-info/SOURCES.txt' reading manifest file 'hello.egg-info/SOURCES.txt' writing manifest file 'hello.egg-info/SOURCES.txt' Copying hello.egg-info to build/bdist.linux-x86_64/wheel/hello-0.0.0-py3.8.egg-info running install_scripts creating build/bdist.linux-x86_64/wheel/hello-0.0.0.dist-info/WHEEL creating 'dist/hello-0.0.0-py3-none-any.whl' and adding 'build/bdist.linux-x86_64/wheel' to it adding 'hello-0.0.0.dist-info/METADATA' adding 'hello-0.0.0.dist-info/WHEEL' adding 'hello-0.0.0.dist-info/top_level.txt' adding 'hello-0.0.0.dist-info/RECORD' removing build/bdist.linux-x86_64/wheel = (1) Install ================================================================== Processing ./dist/hello-0.0.0-py3-none-any.whl Installing collected packages: hello Successfully installed hello-0.0.0 = (2) 2 .dist-info dirs (expected) ============================================= = (2) Build ==================================================================== running bdist_wheel running build installing to build/bdist.linux-x86_64/wheel running install running install_egg_info running egg_info writing hello.egg-info/PKG-INFO writing dependency_links to hello.egg-info/dependency_links.txt writing top-level names to hello.egg-info/top_level.txt reading manifest file 'hello.egg-info/SOURCES.txt' writing manifest file 'hello.egg-info/SOURCES.txt' Copying hello.egg-info to build/bdist.linux-x86_64/wheel/hello-0.0.0-py3.8.egg-info running install_scripts creating build/bdist.linux-x86_64/wheel/hello-0.0.0.dist-info/WHEEL creating 'dist/hello-0.0.0-py3-none-any.whl' and adding 'build/bdist.linux-x86_64/wheel' to it adding 'hello-0.0.0.dist-info/METADATA' adding 'hello-0.0.0.dist-info/WHEEL' adding 'hello-0.0.0.dist-info/top_level.txt' adding 'hello-0.0.0.dist-info/RECORD' removing build/bdist.linux-x86_64/wheel = (2) Add second .dist-info (shared prefix) ==================================== adding: hello-example-0.0.0.dist-info/ (stored 0%) = (2) Install ================================================================== Processing ./dist/hello-0.0.0-py3-none-any.whl Installing collected packages: hello ERROR: Exception: Traceback (most recent call last): File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 153, in _main status = self.run(options, args) File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 446, in run installed = install_given_reqs( File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/req/__init__.py", line 58, in install_given_reqs requirement.install( File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 858, in install self.move_wheel_files( File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 487, in move_wheel_files wheel.move_wheel_files( File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/wheel.py", line 461, in move_wheel_files clobber(source, lib_dir, True) File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/wheel.py", line 408, in clobber assert not info_dir, ('Multiple .dist-info directories: ' + AssertionError: Multiple .dist-info directories: /tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/hello-example-0.0.0.dist-info, /tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/hello-0.0.0.dist-info = (3) 2 .dist-info dirs (NOT expected) ========================================= = (3) Build ==================================================================== running bdist_wheel running build installing to build/bdist.linux-x86_64/wheel running install running install_egg_info running egg_info writing hello.egg-info/PKG-INFO writing dependency_links to hello.egg-info/dependency_links.txt writing top-level names to hello.egg-info/top_level.txt reading manifest file 'hello.egg-info/SOURCES.txt' writing manifest file 'hello.egg-info/SOURCES.txt' Copying hello.egg-info to build/bdist.linux-x86_64/wheel/hello-0.0.0-py3.8.egg-info running install_scripts creating build/bdist.linux-x86_64/wheel/hello-0.0.0.dist-info/WHEEL creating 'dist/hello-0.0.0-py3-none-any.whl' and adding 'build/bdist.linux-x86_64/wheel' to it adding 'hello-0.0.0.dist-info/METADATA' adding 'hello-0.0.0.dist-info/WHEEL' adding 'hello-0.0.0.dist-info/top_level.txt' adding 'hello-0.0.0.dist-info/RECORD' removing build/bdist.linux-x86_64/wheel = (3) Add second .dist-info (no shared prefix) ================================= adding: goodbye-example-0.0.0.dist-info/ (stored 0%) = (3) Install ================================================================== Processing ./dist/hello-0.0.0-py3-none-any.whl Installing collected packages: hello Successfully installed hello-0.0.0 ``` </details> The unexpected case is `(3) Install` - the installation should not go through since there are multiple `.dist-info` directories.
Does pip allow multiple dist-info dirs (in general) to handle installing from flat directory? (It’s the case IIRC.) I kind of feel the responsibility to produce a valid wheel should fall on to the wheel *builder* (so build backend). pip can be free to interpret and invalid wheel and do what’s most comfortable (e.g. choose one by whatever logic, as the current behaviour) since the input already breaks the contract. It is also a valid behaviour to error out as well, but I wouldn’t say it’s necessary. I think erroring out results in the best end-user experience here -- you gave pip something invalid, so it did the wrong thing vs you gave pip something invalid and it refused to use it. > Does pip allow multiple dist-info dirs (in general) to handle installing from flat directory? Good question. The current behavior is [here](https://github.com/pypa/pip/blob/81805a5776767b17533afc934121968f3c03a4d9/src/pip/_internal/operations/build/metadata_legacy.py#L61-L78) - we essentially guess. I think this use case is different from installing a wheel because the wheel format has a spec and we control everything about the directory it is unpacked into. > I kind of feel the responsibility to produce a valid wheel should fall on to the wheel _builder_ (so build backend). Agreed. > pip can be free to interpret and invalid wheel and do what’s most comfortable I am trying to refactor some of our wheel installation logic. The purpose of calling out the expected behavior here is to make it easier to make things more comfortable. :) Our current validation approach has lead to situations like this one, but extracting it while preserving the exact same behavior would result in code that is harder to follow and doesn't really map to the spec. I expect taking the stricter approach will lead to fewer "print better errors" issues, since we can print a nice error upfront, at least in this case. I’m totally on board if the behaviour change would improve the code quality.
2019-12-16T23:35:07Z
[]
[]
Traceback (most recent call last): File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 153, in _main status = self.run(options, args) File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 446, in run installed = install_given_reqs( File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/req/__init__.py", line 58, in install_given_reqs requirement.install( File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 858, in install self.move_wheel_files( File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 487, in move_wheel_files wheel.move_wheel_files( File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/wheel.py", line 461, in move_wheel_files clobber(source, lib_dir, True) File "/tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/pip/_internal/wheel.py", line 408, in clobber assert not info_dir, ('Multiple .dist-info directories: ' + AssertionError: Multiple .dist-info directories: /tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/hello-example-0.0.0.dist-info, /tmp/user/1000/tmp.bXrdYptdl9/env/lib/python3.8/site-packages/hello-0.0.0.dist-info
17,534
pypa/pip
pypa__pip-8025
62c822dc78c2cb04563f726f6a40b4f4e8dae9b0
diff --git a/src/pip/_internal/utils/filesystem.py b/src/pip/_internal/utils/filesystem.py --- a/src/pip/_internal/utils/filesystem.py +++ b/src/pip/_internal/utils/filesystem.py @@ -158,10 +158,13 @@ def _test_writable_dir_win(path): file = os.path.join(path, name) try: fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) + # Python 2 doesn't support FileExistsError and PermissionError. except OSError as e: + # exception FileExistsError if e.errno == errno.EEXIST: continue - if e.errno == errno.EPERM: + # exception PermissionError + if e.errno == errno.EPERM or e.errno == errno.EACCES: # This could be because there's a directory with the same name. # But it's highly unlikely there's a directory called that, # so we'll assume it's because the parent dir is not writable.
Installing packages with non-privileged users on Windows, failed with PermissionError **Environment** * pip version: 20.0.2 * Python version: 3.8.2 * OS: Windows 10 <!-- Feel free to add more information about your environment here --> **Description** <!-- A clear and concise description of what the bug is. --> Installing packages with non-privileged users on Windows, failed with PermissionError. **Expected behavior** <!-- A clear and concise description of what you expected to happen. --> Should detect site-packages folder is not writable, try install to user appdata folder instead. **How to Reproduce** <!-- Describe the steps to reproduce this bug. --> Run `pip install pandas` with non-privileged user on windows. **Output** ``` ERROR: Exception: Traceback (most recent call last): File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 253, in run options.use_user_site = decide_user_install( File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 548, in site_packages_writable return all( File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 549, in <genexpr> test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'c:\\program files (x86)\\python38-32\\Lib\\site-packages\\accesstest_deleteme_fishfingers_custard_m59lch' ``` With pdb I notice `os.open` raise a `OSError` which `errno` is `errno.EACCES`.
Related to https://github.com/pypa/pip/issues/1668
2020-04-12T03:51:10Z
[]
[]
Traceback (most recent call last): File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 253, in run options.use_user_site = decide_user_install( File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 548, in site_packages_writable return all( File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 549, in <genexpr> test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "c:\program files (x86)\python38-32\lib\site-packages\pip\_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'c:\\program files (x86)\\python38-32\\Lib\\site-packages\\accesstest_deleteme_fishfingers_custard_m59lch'
17,563
pypa/pip
pypa__pip-8062
6aa9b8965821ca28b6130c6991a0a609674f154f
diff --git a/src/pip/_internal/operations/install/wheel.py b/src/pip/_internal/operations/install/wheel.py --- a/src/pip/_internal/operations/install/wheel.py +++ b/src/pip/_internal/operations/install/wheel.py @@ -262,7 +262,11 @@ def _record_to_fs_path(record_path): def _fs_to_record_path(path, relative_to=None): # type: (text_type, Optional[text_type]) -> RecordPath if relative_to is not None: - path = os.path.relpath(path, relative_to) + # On Windows, do not handle relative paths if they belong to different + # logical disks + if os.path.splitdrive(path)[0].lower() == \ + os.path.splitdrive(relative_to)[0].lower(): + path = os.path.relpath(path, relative_to) path = path.replace(os.path.sep, '/') return cast('RecordPath', path)
Unable to install package on different logical disk * Pip version: 20.0.1/19.3.1 * Python version: Python 3.6.8 * Operating system: Win10 64-bit, build 18362.535. While executing (note two different logical disks) `F:\temp\.venv\Scripts\pip install --prefix "C:\temp" "greenlet>=0.4.14"` pip exits with an unhandled exception: ``` Collecting greenlet>=0.4.14 Using cached greenlet-0.4.15-cp36-cp36m-win_amd64.whl (16 kB) Installing collected packages: greenlet ERROR: Exception: Traceback (most recent call last): File "...\.venv\lib\site-packages\pip\_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "...\.venv\lib\site-packages\pip\_internal\commands\install.py", line 404, in run use_user_site=options.use_user_site, File "...\.venv\lib\site-packages\pip\_internal\req\__init__.py", line 71, in install_given_reqs **kwargs File "...\.venv\lib\site-packages\pip\_internal\req\req_install.py", line 815, in install warn_script_location=warn_script_location, File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 614, in install_wheel warn_script_location=warn_script_location, File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 447, in install_unpacked_wheel clobber(source, dest, False, fixer=fixer, filter=filter) File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 412, in clobber record_installed(srcfile, destfile, changed) File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 345, in record_installed newpath = normpath(destfile, lib_dir) File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 52, in normpath return os.path.relpath(src, p).replace(os.path.sep, '/') File "...\.venv\lib\ntpath.py", line 584, in relpath path_drive, start_drive)) ValueError: path is on mount 'f:', start on mount 'c:' ``` Because of this I'm unable to install gevent==1.5a2, which executes the command above while installing build dependencies. **Steps to reproduce (cmd)** ``` > virtualenv f:\somewhere\venv > f:\somewhere\venv\Scripts\pip install gevent==1.5a2 ... ValueError: path is on mount 'f:', start on mount 'c:' ``` Seems like not reproducible with different python versions.
FYI, the same issue also seems to occur on my side if my temp directory (`%TEMP%`), where the pep517 isolated build occurs, is on another logical disk. Can be reproduced with `pip install gevent==1.5a4` (which only has a .tar.gz sdist uploaded at the moment of writting this reply). Also: ``` Package Version ---------- ------- pip 20.0.2 setuptools 44.0.0 wheel 0.34.2 ``` Some investigation notes before I leave this issue for now. The error occurs when pip is copying contents from data directories, which is weird because the built 1.5a4 wheels on PyPI (they have a few now) don’t contain any `.data` directories. I’m not sure what I’m missing 🤔
2020-04-16T13:10:48Z
[]
[]
Traceback (most recent call last): File "...\.venv\lib\site-packages\pip\_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "...\.venv\lib\site-packages\pip\_internal\commands\install.py", line 404, in run use_user_site=options.use_user_site, File "...\.venv\lib\site-packages\pip\_internal\req\__init__.py", line 71, in install_given_reqs **kwargs File "...\.venv\lib\site-packages\pip\_internal\req\req_install.py", line 815, in install warn_script_location=warn_script_location, File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 614, in install_wheel warn_script_location=warn_script_location, File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 447, in install_unpacked_wheel clobber(source, dest, False, fixer=fixer, filter=filter) File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 412, in clobber record_installed(srcfile, destfile, changed) File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 345, in record_installed newpath = normpath(destfile, lib_dir) File "...\.venv\lib\site-packages\pip\_internal\operations\install\wheel.py", line 52, in normpath return os.path.relpath(src, p).replace(os.path.sep, '/') File "...\.venv\lib\ntpath.py", line 584, in relpath path_drive, start_drive)) ValueError: path is on mount 'f:', start on mount 'c:'
17,570
pypa/pip
pypa__pip-8079
97f639057ec0855804c5cb53423ac74394cdefc6
diff --git a/src/pip/_internal/resolution/resolvelib/requirements.py b/src/pip/_internal/resolution/resolvelib/requirements.py --- a/src/pip/_internal/resolution/resolvelib/requirements.py +++ b/src/pip/_internal/resolution/resolvelib/requirements.py @@ -77,7 +77,11 @@ def is_satisfied_by(self, candidate): assert candidate.name == self.name, \ "Internal issue: Candidate is not for this requirement " \ " {} vs {}".format(candidate.name, self.name) - return candidate.version in self._ireq.req.specifier + # We can safely always allow prereleases here since PackageFinder + # already implements the prerelease logic, and would have filtered out + # prerelease candidates if the user does not expect them. + spec = self._ireq.req.specifier + return spec.contains(candidate.version, prereleases=True) class RequiresPythonRequirement(Requirement): @@ -109,4 +113,7 @@ def find_matches(self): def is_satisfied_by(self, candidate): # type: (Candidate) -> bool assert candidate.name == self._candidate.name, "Not Python candidate" - return candidate.version in self.specifier + # We can safely always allow prereleases here since PackageFinder + # already implements the prerelease logic, and would have filtered out + # prerelease candidates if the user does not expect them. + return self.specifier.contains(candidate.version, prereleases=True)
New resolver cannot installs distributions that only have pre releases **Environment** * pip version: master, today * Python version: 3 * OS: linux **Description** I want to install a distribution that only has pre-releases. The legacy resolver does support this. The new one does not. Note: using `--pre` does not seem to influence the result. The legacy resolver could install such distributions without using `--pre`. **Expected behavior** Installation should succeed. **How to Reproduce** ```console $ pip install --no-deps odoo13-addon-date-range --unstable-feature=resolver ERROR: Exception: Traceback (most recent call last): File "/home/me/pip/src/pip/_internal/cli/base_command.py", line 199, in _main status = self.run(options, args) File "/home/me/pip/src/pip/_internal/cli/req_command.py", line 185, in wrapper return func(self, options, args) File "/home/me/pip/src/pip/_internal/commands/install.py", line 333, in run reqs, check_supported_wheels=not options.target_dir File "/home/me/pip/src/pip/_internal/resolution/resolvelib/resolver.py", line 80, in resolve self._result = resolver.resolve(requirements) File "/home/me/pip/src/pip/_vendor/resolvelib/resolvers.py", line 413, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "/home/me/pip/src/pip/_vendor/resolvelib/resolvers.py", line 310, in resolve failure_causes = self._attempt_to_pin_criterion(name, criterion) File "/home/me/pip/src/pip/_vendor/resolvelib/resolvers.py", line 240, in _attempt_to_pin_criterion raise InconsistentCandidate(candidate, criterion) pip._vendor.resolvelib.resolvers.InconsistentCandidate: Provided candidate LinkCandidate('https://files.pythonhosted.org/packages/1f/0b/945335a37082b6b013cc1331f49e3f5b6a18cdd0b693475e6ca9e9a7df6e/odoo13_addon_date_range-13.0.1.0.1.dev8-py3-none-any.whl#sha256=3883bbe87db8d5db4364e8a42e86546e19e8e4f123d98c4e9454587dfa9401df (from https://pypi.org/simple/odoo13-addon-date-range/) (requires-python:>=3.5)') does not satisfy SpecifierRequirement('odoo13-addon-date-range') ``` Note I used `--no-deps` because a dependency is not on pypi, but that has no influence on the result.
`InconsistentCandidate` is raised if a match from `find_matches()` does not return true for `is_satisfied_by()`. So my guess is we need to fix `is_satisfied_by()` to accept prereleases. Nice catch @sbidoul! ^>^ I don't think this needs to be fixed *right now* prior to pip 20.1's beta, but yes, we do have to implement this eventually. :) It would also fail with `--pre` if the selected version is a prerelease. Not all prereleases fail though, only if the specifier does not contain a prerelease. I think I have a fix.
2020-04-18T15:09:34Z
[]
[]
Traceback (most recent call last): File "/home/me/pip/src/pip/_internal/cli/base_command.py", line 199, in _main status = self.run(options, args) File "/home/me/pip/src/pip/_internal/cli/req_command.py", line 185, in wrapper return func(self, options, args) File "/home/me/pip/src/pip/_internal/commands/install.py", line 333, in run reqs, check_supported_wheels=not options.target_dir File "/home/me/pip/src/pip/_internal/resolution/resolvelib/resolver.py", line 80, in resolve self._result = resolver.resolve(requirements) File "/home/me/pip/src/pip/_vendor/resolvelib/resolvers.py", line 413, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "/home/me/pip/src/pip/_vendor/resolvelib/resolvers.py", line 310, in resolve failure_causes = self._attempt_to_pin_criterion(name, criterion) File "/home/me/pip/src/pip/_vendor/resolvelib/resolvers.py", line 240, in _attempt_to_pin_criterion raise InconsistentCandidate(candidate, criterion) pip._vendor.resolvelib.resolvers.InconsistentCandidate: Provided candidate LinkCandidate('https://files.pythonhosted.org/packages/1f/0b/945335a37082b6b013cc1331f49e3f5b6a18cdd0b693475e6ca9e9a7df6e/odoo13_addon_date_range-13.0.1.0.1.dev8-py3-none-any.whl#sha256=3883bbe87db8d5db4364e8a42e86546e19e8e4f123d98c4e9454587dfa9401df (from https://pypi.org/simple/odoo13-addon-date-range/) (requires-python:>=3.5)') does not satisfy SpecifierRequirement('odoo13-addon-date-range')
17,572
pypa/pip
pypa__pip-8083
80c640b5a892ad5e3258ff7f83f63c6fdfecb1de
diff --git a/src/pip/_internal/index/collector.py b/src/pip/_internal/index/collector.py --- a/src/pip/_internal/index/collector.py +++ b/src/pip/_internal/index/collector.py @@ -455,8 +455,9 @@ def _get_html_page(link, session=None): 'be checked by HEAD.', link, ) except _NotHTML as exc: - logger.debug( - 'Skipping page %s because the %s request got Content-Type: %s', + logger.warning( + 'Skipping page %s because the %s request got Content-Type: %s.' + 'The only supported Content-Type is text/html', link, exc.request_desc, exc.content_type, ) except HTTPError as exc:
Pip silently ignores index pages with unexpected content type **Environment** * pip version: 19.1.1 * Python version: 3.7.2 * OS: Ubuntu Linux 18.04 <!-- Feel free to add more information about your environment here --> **Description** As mentioned in #6697, if a package index page configured via `--index-url` returns an unexpected content type, then pip silently ignores it and displays a generic "No matching distribution found" error message. **Expected behavior** pip should display a warning in the event that the content returned by the package index is ill-formed or not understood. **How to Reproduce** <details> <summary><b>repro.sh</b></summary> ``` #!/bin/sh cd $(mktemp -d) python -m venv .venv . .venv/bin/activate pip install --upgrade pip cat <<EOF > server.py from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('content-type', 'application/xhtml+xml') self.end_headers() if __name__ == '__main__': server = ThreadingHTTPServer(('localhost', 11111), Handler) server.serve_forever() EOF python server.py >/dev/null 2>&1 & echo ========== run 1 ========== pip install --index-url=http://localhost:11111/ requests echo ========== run 2 ========== pip install --verbose --index-url=http://localhost:11111/ requests ``` </details> **Output** <details> <summary>run 1</summary> ``` Looking in indexes: http://localhost:11111/ Collecting requests ERROR: Could not find a version that satisfies the requirement requests (from versions: none) ERROR: No matching distribution found for requests ``` </details> <details> <summary>run 2 (verbose)</summary> ``` Created temporary directory: /tmp/user/1000/pip-ephem-wheel-cache-nz_lnbof Created temporary directory: /tmp/user/1000/pip-req-tracker-68gx3hw_ Created requirements tracker '/tmp/user/1000/pip-req-tracker-68gx3hw_' Created temporary directory: /tmp/user/1000/pip-install-3cazkrz9 Looking in indexes: http://localhost:11111/ Collecting requests 1 location(s) to search for versions of requests: * http://localhost:11111/requests/ Getting page http://localhost:11111/requests/ Starting new HTTP connection (1): localhost:11111 http://localhost:11111 "GET /requests/ HTTP/1.1" 200 None Skipping page http://localhost:11111/requests/ because the GET request got Content-Type: application/xhtml+xml ERROR: Could not find a version that satisfies the requirement requests (from versions: none) Cleaning up... Removed build tracker '/tmp/user/1000/pip-req-tracker-68gx3hw_' ERROR: No matching distribution found for requests Exception information: Traceback (most recent call last): File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 178, in main status = self.run(options, args) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/commands/install.py", line 352, in run resolver.resolve(requirement_set) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/resolve.py", line 131, in resolve self._resolve_one(requirement_set, req) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/resolve.py", line 294, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/resolve.py", line 242, in _get_abstract_dist_for self.require_hashes File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 282, in prepare_linked_requirement req.populate_link(finder, upgrade_allowed, require_hashes) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/req/req_install.py", line 198, in populate_link self.link = finder.find_requirement(self, upgrade) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/index.py", line 792, in find_requirement 'No matching distribution found for %s' % req pip._internal.exceptions.DistributionNotFound: No matching distribution found for requests ``` </details> Specifically, the issue is that the message > Skipping page http://localhost:11111/requests/ because the GET request got Content-Type: application/xhtml+xml only shows up with `--verbose`.
Is this PR just a change from `logger.debug` to `logger.warning`? If yes I would like to take it up At first glance this should be useful improvement, yes. We may want to add a mention of the supported content types in the error message. Thanks, and it looks like `text/html` is the only acceptable header as per https://github.com/pypa/pip/blob/97f639057ec0855804c5cb53423ac74394cdefc6/src/pip/_internal/index/collector.py#L98-L106
2020-04-19T09:33:53Z
[]
[]
Traceback (most recent call last): File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 178, in main status = self.run(options, args) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/commands/install.py", line 352, in run resolver.resolve(requirement_set) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/resolve.py", line 131, in resolve self._resolve_one(requirement_set, req) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/resolve.py", line 294, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/resolve.py", line 242, in _get_abstract_dist_for self.require_hashes File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 282, in prepare_linked_requirement req.populate_link(finder, upgrade_allowed, require_hashes) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/req/req_install.py", line 198, in populate_link self.link = finder.find_requirement(self, upgrade) File "/tmp/user/1000/tmp.ubtUD2yfZP/.venv/lib/python3.7/site-packages/pip/_internal/index.py", line 792, in find_requirement 'No matching distribution found for %s' % req pip._internal.exceptions.DistributionNotFound: No matching distribution found for requests
17,573
pypa/pip
pypa__pip-8124
daff81124ab76138da323a5173b120dd88190f56
diff --git a/src/pip/_internal/commands/cache.py b/src/pip/_internal/commands/cache.py --- a/src/pip/_internal/commands/cache.py +++ b/src/pip/_internal/commands/cache.py @@ -48,6 +48,11 @@ def run(self, options, args): "purge": self.purge_cache, } + if not options.cache_dir: + logger.error("pip cache commands can not " + "function since cache is disabled.") + return ERROR + # Determine action if not args or args[0] not in handlers: logger.error("Need an action ({}) to perform.".format(
'pip cache info' fails when no-cache-dir set pip version: pip 20.1b1 Python version: CPython 3.8.1 OS: Win 10 64 Testing 20.1 beta, execute 'pip cache info' and crashes. I'm guessing it's due to pip.ini turning off caching. pip.ini: ``` [global] no-cache-dir = false ``` Command execution: ``` > pip cache info ERROR: Exception: Traceback (most recent call last): File "c:\program files\python38\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in _main status = self.run(options, args) File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 62, in run handlers[action](options, args[1:]) File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 74, in get_cache_info num_packages = len(self._find_wheels(options, '*')) File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 145, in _find_wheels wheel_dir = self._wheels_cache_dir(options) File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 141, in _wheels_cache_dir return os.path.join(options.cache_dir, 'wheels') File "c:\program files\python38\lib\ntpath.py", line 78, in join path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not bool ```
@efahl Thanks for the report! This will hold true for all `pip cache` commands, if we disable the cache via `--no-cache-dir`, since there is no cache to operate on as the user has explicitly disabled it. e.g. ``` $ pip cache list twine* --no-cache-dir ERROR: Exception: Traceback (most recent call last): File "/Users/devesh/pip/src/pip/_internal/cli/base_command.py", line 188, in _main status = self.run(options, args) File "/Users/devesh/pip/src/pip/_internal/commands/cache.py", line 62, in run handlers[action](options, args[1:]) File "/Users/devesh/pip/src/pip/_internal/commands/cache.py", line 101, in list_cache_items files = self._find_wheels(options, pattern) File "/Users/devesh/pip/src/pip/_internal/commands/cache.py", line 145, in _find_wheels wheel_dir = self._wheels_cache_dir(options) File "/Users/devesh/pip/src/pip/_internal/commands/cache.py", line 141, in _wheels_cache_dir return os.path.join(options.cache_dir, 'wheels') File "/Users/devesh/.pyenv/versions/3.8.2/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not bool ``` ``` $ pip cache remove twine* --no-cache-dir ERROR: Exception: Traceback (most recent call last): File "/Users/devesh/pip/src/pip/_internal/cli/base_command.py", line 188, in _main status = self.run(options, args) File "/Users/devesh/pip/src/pip/_internal/commands/cache.py", line 62, in run handlers[action](options, args[1:]) File "/Users/devesh/pip/src/pip/_internal/commands/cache.py", line 123, in remove_cache_items files = self._find_wheels(options, args[0]) File "/Users/devesh/pip/src/pip/_internal/commands/cache.py", line 145, in _find_wheels wheel_dir = self._wheels_cache_dir(options) File "/Users/devesh/pip/src/pip/_internal/commands/cache.py", line 141, in _wheels_cache_dir return os.path.join(options.cache_dir, 'wheels') File "/Users/devesh/.pyenv/versions/3.8.2/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not bool ``` So should we raise a warning in [pip.internal.commands.cache.run](https://github.com/pypa/pip/blob/master/src/pip/_internal/commands/cache.py#L42) stating that `pip cache commands won't function since the cache is disabled. <steps to enable the cache>` when we detect that `options.cache_dir == False` ?
2020-04-24T09:37:27Z
[]
[]
Traceback (most recent call last): File "c:\program files\python38\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in _main status = self.run(options, args) File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 62, in run handlers[action](options, args[1:]) File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 74, in get_cache_info num_packages = len(self._find_wheels(options, '*')) File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 145, in _find_wheels wheel_dir = self._wheels_cache_dir(options) File "c:\program files\python38\lib\site-packages\pip\_internal\commands\cache.py", line 141, in _wheels_cache_dir return os.path.join(options.cache_dir, 'wheels') File "c:\program files\python38\lib\ntpath.py", line 78, in join path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not bool
17,576
pypa/pip
pypa__pip-8144
6a7bf9477681d133467740568e24a6382dc4e29c
diff --git a/src/pip/_internal/operations/install/wheel.py b/src/pip/_internal/operations/install/wheel.py --- a/src/pip/_internal/operations/install/wheel.py +++ b/src/pip/_internal/operations/install/wheel.py @@ -8,6 +8,7 @@ import collections import compileall +import contextlib import csv import logging import os.path @@ -32,17 +33,18 @@ from pip._internal.utils.misc import captured_stdout, ensure_dir, hash_file from pip._internal.utils.temp_dir import TempDirectory from pip._internal.utils.typing import MYPY_CHECK_RUNNING -from pip._internal.utils.unpacking import unpack_file +from pip._internal.utils.unpacking import current_umask, unpack_file from pip._internal.utils.wheel import parse_wheel if MYPY_CHECK_RUNNING: from email.message import Message from typing import ( Dict, List, Optional, Sequence, Tuple, Any, - Iterable, Callable, Set, + Iterable, Iterator, Callable, Set, ) from pip._internal.models.scheme import Scheme + from pip._internal.utils.filesystem import NamedTemporaryFileResult InstalledCSVRow = Tuple[str, ...] @@ -565,19 +567,27 @@ def is_entrypoint_wrapper(name): if msg is not None: logger.warning(msg) + generated_file_mode = 0o666 - current_umask() + + @contextlib.contextmanager + def _generate_file(path, **kwargs): + # type: (str, **Any) -> Iterator[NamedTemporaryFileResult] + with adjacent_tmp_file(path, **kwargs) as f: + yield f + os.chmod(f.name, generated_file_mode) + replace(f.name, path) + # Record pip as the installer installer_path = os.path.join(dest_info_dir, 'INSTALLER') - with adjacent_tmp_file(installer_path) as installer_file: + with _generate_file(installer_path) as installer_file: installer_file.write(b'pip\n') - replace(installer_file.name, installer_path) generated.append(installer_path) # Record the PEP 610 direct URL reference if direct_url is not None: direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME) - with adjacent_tmp_file(direct_url_path) as direct_url_file: + with _generate_file(direct_url_path) as direct_url_file: direct_url_file.write(direct_url.to_json().encode("utf-8")) - replace(direct_url_file.name, direct_url_path) generated.append(direct_url_path) # Record details of all files installed @@ -589,10 +599,9 @@ def is_entrypoint_wrapper(name): changed=changed, generated=generated, lib_dir=lib_dir) - with adjacent_tmp_file(record_path, **csv_io_kwargs('w')) as record_file: + with _generate_file(record_path, **csv_io_kwargs('w')) as record_file: writer = csv.writer(record_file) writer.writerows(sorted_outrows(rows)) # sort to simplify testing - replace(record_file.name, record_path) def install_wheel(
PEP 610 support (git packages) can break pip freeze First of all, great job guys on adding PEP 610 support, this is really awesome ! But, if you install a *git package* with `sudo`, it will cause any non root `pip freeze` to crash **Environment** * pip version: 20.1b1 * Python version: 3.6 * OS: Ubuntu If you do ```console sudo pip install git+https://github.com/... ``` Then when you run `pip freeze` (notice without `sudo`) You get the following exception: ``` ERROR: Exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 188, in _main status = self.run(options, args) File "/usr/local/lib/python3.6/site-packages/pip/_internal/commands/freeze.py", line 98, in run for line in freeze(**freeze_kwargs): File "/usr/local/lib/python3.6/site-packages/pip/_internal/operations/freeze.py", line 68, in freeze req = FrozenRequirement.from_dist(dist) File "/usr/local/lib/python3.6/site-packages/pip/_internal/operations/freeze.py", line 256, in from_dist direct_url = dist_get_direct_url(dist) File "/usr/local/lib/python3.6/site-packages/pip/_internal/utils/direct_url_helpers.py", line 118, in dist_get_direct_url return DirectUrl.from_json(dist.get_metadata(DIRECT_URL_METADATA_NAME)) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1420, in get_metadata value = self._get(path) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1616, in _get with open(path, 'rb') as stream: PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.6/site-packages/trains-0.14.1.dist-info/direct_url.json' ``` As you can see the `direct_url.json` file is missing the r flag for group / others , which raises the exception. ``` -rw------- 1 root root 135 Apr 25 23:22 /usr/local/lib/python3.6/site-packages/trains-0.14.1.dist-info/direct_url.json ``` I tested running `chmod 644` on this file, and after that `pip freeze` works like a charm. For reference, the `top_level.txt` file that is next to the `direct_url.json` has the correct permission
For completeness, does the `RECORD` file has the same permission? Most files in`.dist-info` are extracted from the wheel, and get their permission fixed during the process. But these two are written from scratch, and should be in a similar situation. (Note for implementer: the permission fix for files extracted from wheel is in `pip._internal.utils.unpacking`) @uranusjr see below full listing of the directory ```bash ll /usr/local/lib/python3.6/site-packages/trains-0.14.1.dist-info/ total 72K -rw------- 1 root root 135 Apr 26 02:05 direct_url.json -rw-r--r-- 1 root root 69 Apr 26 02:05 entry_points.txt -rw------- 1 root root 4 Apr 26 02:05 INSTALLER -rw-r--r-- 1 root root 12K Apr 26 02:05 LICENSE -rw-r--r-- 1 root root 11K Apr 26 02:05 METADATA -rw------- 1 root root 26K Apr 26 02:05 RECORD -rw-r--r-- 1 root root 7 Apr 26 02:05 top_level.txt -rw-r--r-- 1 root root 110 Apr 26 02:05 WHEEL ``` The permissions shown as per above comment also hold true when performing a pip install without sudo using a git VCS URL, but the pip freeze doesn't crash in this case ``` $ pip --version pip 20.1.dev1 from /Users/devesh/pip/src/pip (python 3.8) $ python --version Python 3.8.2 $ pip install git+https://github.com/pypa/twine#egg=master Collecting master Cloning https://github.com/pypa/twine to /private/var/folders/xg/blp845_s0xn093dyrtgy936h0000gp/T/pip-install-d7wn0lz6/master Running command git clone -q https://github.com/pypa/twine /private/var/folders/xg/blp845_s0xn093dyrtgy936h0000gp/T/pip-install-d7wn0lz6/master Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done WARNING: Generating metadata for package master produced metadata for project name twine. Fix your #egg=master fragments. Requirement already satisfied: requests>=2.20 in ./.env/lib/python3.8/site-packages (from twine) (2.23.0) Requirement already satisfied: requests-toolbelt!=0.9.0,>=0.8.0 in ./.env/lib/python3.8/site-packages (from twine) (0.9.1) Requirement already satisfied: pkginfo>=1.4.2 in ./.env/lib/python3.8/site-packages (from twine) (1.5.0.1) Requirement already satisfied: keyring>=15.1 in ./.env/lib/python3.8/site-packages (from twine) (21.2.0) Requirement already satisfied: setuptools>=0.7.0 in ./.env/lib/python3.8/site-packages (from twine) (41.2.0) Requirement already satisfied: readme-renderer>=21.0 in ./.env/lib/python3.8/site-packages (from twine) (26.0) Requirement already satisfied: tqdm>=4.14 in ./.env/lib/python3.8/site-packages (from twine) (4.45.0) Requirement already satisfied: idna<3,>=2.5 in ./.env/lib/python3.8/site-packages (from requests>=2.20->twine) (2.9) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in ./.env/lib/python3.8/site-packages (from requests>=2.20->twine) (1.25.9) Requirement already satisfied: chardet<4,>=3.0.2 in ./.env/lib/python3.8/site-packages (from requests>=2.20->twine) (3.0.4) Requirement already satisfied: certifi>=2017.4.17 in ./.env/lib/python3.8/site-packages (from requests>=2.20->twine) (2020.4.5.1) Requirement already satisfied: docutils>=0.13.1 in ./.env/lib/python3.8/site-packages (from readme-renderer>=21.0->twine) (0.16) Requirement already satisfied: Pygments>=2.5.1 in ./.env/lib/python3.8/site-packages (from readme-renderer>=21.0->twine) (2.6.1) Requirement already satisfied: six in ./.env/lib/python3.8/site-packages (from readme-renderer>=21.0->twine) (1.14.0) Requirement already satisfied: bleach>=2.1.0 in ./.env/lib/python3.8/site-packages (from readme-renderer>=21.0->twine) (3.1.4) Requirement already satisfied: webencodings in ./.env/lib/python3.8/site-packages (from bleach>=2.1.0->readme-renderer>=21.0->twine) (0.5.1) Building wheels for collected packages: twine, twine Building wheel for twine (PEP 517) ... done Created wheel for twine: filename=twine-3.1.2.dev52+g2cec216-py3-none-any.whl size=36679 sha256=72ec0b185e4b51d5e5e95860a68b81daf25d3cbe83667a79a8649a0eec04622a Stored in directory: /private/var/folders/xg/blp845_s0xn093dyrtgy936h0000gp/T/pip-ephem-wheel-cache-t4yq_ai4/wheels/73/dd/fb/3039711df8645ab0ccc3e7d5f834289bf9ee7569c222c1fbc4 Building wheel for twine (PEP 517) ... done Created wheel for twine: filename=twine-3.1.2.dev52+g2cec216-py3-none-any.whl size=36679 sha256=90d3e0d5596caa33d2cc171f611f1c1430450a66085ec72d5fcda503a09c9806 Stored in directory: /private/var/folders/xg/blp845_s0xn093dyrtgy936h0000gp/T/pip-ephem-wheel-cache-t4yq_ai4/wheels/d4/ae/3f/06dd543cc8064e720fa3f9bcc69f3c644ea7c931864ee2c7b3 Successfully built twine twine Installing collected packages: twine Successfully installed twine-3.1.2.dev52+g2cec216 $ ls -l .env/lib/python3.8/site-packages/twine-3.1.2.dev52+g2cec216.dist-info/ total 104 -rw------- 1 devesh staff 4 Apr 26 10:51 INSTALLER -rw-r--r-- 1 devesh staff 9695 Apr 26 10:51 LICENSE -rw-r--r-- 1 devesh staff 16240 Apr 26 10:51 METADATA -rw------- 1 devesh staff 2811 Apr 26 10:51 RECORD -rw-r--r-- 1 devesh staff 92 Apr 26 10:51 WHEEL -rw------- 1 devesh staff 125 Apr 26 10:51 direct_url.json -rw-r--r-- 1 devesh staff 186 Apr 26 10:51 entry_points.txt -rw-r--r-- 1 devesh staff 6 Apr 26 10:51 top_level.txt $ pip freeze ... twine @ git+https://github.com/pypa/twine@2cec2169faeb9a2906b2288776be91d660561a06 ... ``` The problem has been introduced in #7929 when we started using `adjacent_tmp_file` to create `RECORD`, `direct_url.json` and `INSTALLER`. Files created with `tempfile` functions have restricted permissions to avoid security issues when such files are created in world-readable directories such as `/tmp`. That is something that needs fixing, possibly in 20.1.
2020-04-26T09:30:12Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 188, in _main status = self.run(options, args) File "/usr/local/lib/python3.6/site-packages/pip/_internal/commands/freeze.py", line 98, in run for line in freeze(**freeze_kwargs): File "/usr/local/lib/python3.6/site-packages/pip/_internal/operations/freeze.py", line 68, in freeze req = FrozenRequirement.from_dist(dist) File "/usr/local/lib/python3.6/site-packages/pip/_internal/operations/freeze.py", line 256, in from_dist direct_url = dist_get_direct_url(dist) File "/usr/local/lib/python3.6/site-packages/pip/_internal/utils/direct_url_helpers.py", line 118, in dist_get_direct_url return DirectUrl.from_json(dist.get_metadata(DIRECT_URL_METADATA_NAME)) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1420, in get_metadata value = self._get(path) File "/usr/local/lib/python3.6/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1616, in _get with open(path, 'rb') as stream: PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.6/site-packages/trains-0.14.1.dist-info/direct_url.json'
17,577
pypa/pip
pypa__pip-8291
76b865155ee646927e838c377b46643b51ccd2fd
diff --git a/src/pip/_internal/resolution/resolvelib/candidates.py b/src/pip/_internal/resolution/resolvelib/candidates.py --- a/src/pip/_internal/resolution/resolvelib/candidates.py +++ b/src/pip/_internal/resolution/resolvelib/candidates.py @@ -347,8 +347,8 @@ class ExtrasCandidate(Candidate): to treat it as a separate node in the dependency graph. 2. When we're getting the candidate's dependencies, a) We specify that we want the extra dependencies as well. - b) We add a dependency on the base candidate (matching the name and - version). See below for why this is needed. + b) We add a dependency on the base candidate. + See below for why this is needed. 3. We return None for the underlying InstallRequirement, as the base candidate will provide it, and we don't want to end up with duplicates. @@ -417,6 +417,10 @@ def iter_dependencies(self): extra ) + # Add a dependency on the exact base + # (See note 2b in the class docstring) + yield factory.make_requirement_from_candidate(self.base) + for r in self.base.dist.requires(valid_extras): requirement = factory.make_requirement_from_spec_matching_extras( str(r), self.base._ireq, valid_extras, @@ -424,13 +428,6 @@ def iter_dependencies(self): if requirement: yield requirement - # Add a dependency on the exact base. - # (See note 2b in the class docstring) - # FIXME: This does not work if the base candidate is specified by - # link, e.g. "pip install .[dev]" will fail. - spec = "{}=={}".format(self.base.name, self.base.version) - yield factory.make_requirement_from_spec(spec, self.base._ireq) - def get_install_requirement(self): # type: () -> Optional[InstallRequirement] # We don't return anything here, because we always diff --git a/src/pip/_internal/resolution/resolvelib/factory.py b/src/pip/_internal/resolution/resolvelib/factory.py --- a/src/pip/_internal/resolution/resolvelib/factory.py +++ b/src/pip/_internal/resolution/resolvelib/factory.py @@ -180,12 +180,16 @@ def make_requirement_from_install_req(self, ireq): # TODO: Get name and version from ireq, if possible? # Specifically, this might be needed in "name @ URL" # syntax - need to check where that syntax is handled. - cand = self._make_candidate_from_link( + candidate = self._make_candidate_from_link( ireq.link, extras=set(ireq.extras), parent=ireq, ) - return ExplicitRequirement(cand) + return self.make_requirement_from_candidate(candidate) return SpecifierRequirement(ireq, factory=self) + def make_requirement_from_candidate(self, candidate): + # type: (Candidate) -> ExplicitRequirement + return ExplicitRequirement(candidate) + def make_requirement_from_spec(self, specifier, comes_from): # type: (str, InstallRequirement) -> Requirement ireq = self._make_install_req_from_spec(specifier, comes_from)
pip resolver searches for target itself and fails I did not manage to create a small reproducible of this in isolation, however, something is definitely off. Creating a tox test suite fails for virtualenv project: ```bash git clone https://github.com/pypa/virtualenv env PIP_UNSTABLE_FEATURE="resolver" VIRTUALENV_PIP=20.2b1 tox -re py38 --notest ``` throws: ```bash env PIP_UNSTABLE_FEATURE="resolver" VIRTUALENV_PIP=20.2b1 tox -re py38 --notest .package recreate: /Users/bernat/git/github/virtualenv/.tox/.package .package installdeps: setuptools >= 41.0.0, wheel >= 0.30.0, setuptools_scm >= 2 py38 recreate: /Users/bernat/git/github/virtualenv/.tox/py38 py38 installdeps: pip >= 20.0.2 py38 inst: /Users/bernat/git/github/virtualenv/.tox/.tmp/package/1/virtualenv-20.0.21.dev10+gc364311.tar.gz ERROR: invocation failed (exit code 1), logfile: /Users/bernat/git/github/virtualenv/.tox/py38/log/py38-2.log ================================================================================================================================== log start =================================================================================================================================== Looking in indexes: http://localhost:3141/bernat/bb Processing ./.tox/.tmp/package/1/virtualenv-20.0.21.dev10+gc364311.tar.gz Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'done' ERROR: Could not find a version that satisfies the requirement virtualenv==20.0.21.dev10+gc364311 (from virtualenv[testing]) ERROR: No matching distribution found for virtualenv ``` When switching to verbose mode I can see: ``` Given no hashes to check 0 links for project 'virtualenv': discarding no candidates ERROR: Could not find a version that satisfies the requirement virtualenv==20.0.21.dev10+gc364311 (from virtualenv[testing]) ERROR: No matching distribution found for virtualenv Exception information: Traceback (most recent call last): File "/Users/bernat/git/github/virtualenv/.tox/py38/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 136, in resolve self._result = resolver.resolve( File "/Users/bernat/git/github/virtualenv/.tox/py38/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 413, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "/Users/bernat/git/github/virtualenv/.tox/py38/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 319, in resolve raise ResolutionImpossible(causes) pip._vendor.resolvelib.resolvers.ResolutionImpossible: [RequirementInformation(requirement=SpecifierRequirement('virtualenv==20.0.21.dev10+gc364311'), parent=ExtrasCandidate(base=LinkCandidate('file:///Users/bernat/git/github/virtualenv/.tox/.tmp/package/1/virtualenv-20.0.21.dev10%2Bgc364311.tar.gz'), extras={'testing'}))] ```
Sounds similar to this section of failures: https://hackmd.io/TkGB1hPQTcu9y_4JwAtGyA?view#Direct-URL-with-extras Not sure if we already have a tracking issue for this, so I’m labelling this as a normal bug report. This is definitely a case of non-specifier requirement that has extras (similar to `.[dev]`). I'd argue this isn't a bug as much as it is a TODO for the new resolver. :P We even have a FIXME comment in the code for it. (Which I'm looking at now. When was the last time I said I hate extras? 🙂) I just call all found errors a feature gap compared to the current no dependency resolver 😁 bug or feature, that's detail under the hood. 😎 > (Which I'm looking at now. When was the last time I said I hate extras? 🙂) More than a day ago, so you can say that again. :) > When was the last time I said I hate extras? More than two weeks ago, so definitely allowed again in my case. FWIW, I think have a bugfix branch for this locally, so I'll be filing that sometime next week. (once my college's last report submission is done with)
2020-05-21T15:40:34Z
[]
[]
Traceback (most recent call last): File "/Users/bernat/git/github/virtualenv/.tox/py38/lib/python3.8/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 136, in resolve self._result = resolver.resolve( File "/Users/bernat/git/github/virtualenv/.tox/py38/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 413, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "/Users/bernat/git/github/virtualenv/.tox/py38/lib/python3.8/site-packages/pip/_vendor/resolvelib/resolvers.py", line 319, in resolve raise ResolutionImpossible(causes) pip._vendor.resolvelib.resolvers.ResolutionImpossible: [RequirementInformation(requirement=SpecifierRequirement('virtualenv==20.0.21.dev10+gc364311'), parent=ExtrasCandidate(base=LinkCandidate('file:///Users/bernat/git/github/virtualenv/.tox/.tmp/package/1/virtualenv-20.0.21.dev10%2Bgc364311.tar.gz'), extras={'testing'}))]
17,583
pypa/pip
pypa__pip-8343
57b39a85bccd95c2d09f571365da2326ed6ebdae
diff --git a/src/pip/_internal/operations/install/wheel.py b/src/pip/_internal/operations/install/wheel.py --- a/src/pip/_internal/operations/install/wheel.py +++ b/src/pip/_internal/operations/install/wheel.py @@ -7,6 +7,7 @@ import compileall import contextlib import csv +import io import logging import os.path import re @@ -21,14 +22,7 @@ from pip._vendor import pkg_resources from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor.distlib.util import get_export_entry -from pip._vendor.six import ( - PY2, - StringIO, - ensure_str, - ensure_text, - itervalues, - text_type, -) +from pip._vendor.six import PY2, ensure_str, ensure_text, itervalues, text_type from pip._internal.exceptions import InstallationError from pip._internal.locations import get_major_minor_version @@ -131,11 +125,11 @@ def get_entrypoints(filename): # means that they may or may not be valid INI files. The attempt here is to # strip leading and trailing whitespace in order to make them valid INI # files. - with open(filename) as fp: - data = StringIO() + with io.open(filename, encoding="utf-8") as fp: + data = io.StringIO() for line in fp: data.write(line.strip()) - data.write("\n") + data.write(u"\n") data.seek(0) # get the entry points and then the script names
UnicodeDecodeError when using utf-8 in entry_points **Environment** * pip version: 20.1.1 * Python version: 3.7.6 * OS: win7 pro <!-- Feel free to add more information about your environment here --> **Description** I've a demo package having utf-8 in entry_points: https://github.com/program-in-chinese/study/blob/e08bc8d9cb7e4c6c5f493ef9d43a331fa8f6f766/1-%E5%9F%BA%E7%A1%80/%E5%B0%8F%E6%B8%B8%E6%88%8F/setup.py#L12 It published successfully and installed fine in Mac, but got error when installed in Windows. Not sure if related to https://github.com/pypa/pip/issues/2042 **Expected behavior** Installed successfully without error, just like in Mac. **How to Reproduce** <!-- Describe the steps to reproduce this bug. --> 1. Get package from https://pypi.org/project/demo-game-guess-number/ 2. An error occurs. **Output** ``` >pip install demo-game-guess-number Collecting demo-game-guess-number Using cached demo_game_guess_number-0.0.5-py3-none-any.whl (2.5 kB) Installing collected packages: demo-game-guess-number ERROR: Exception: Traceback (most recent call last): File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\cli\base_command.py", line 188, in _main status = self.run(options, args) File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\cli\req_command.py", line 185, in wrapper return func(self, options, args) File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\commands\install.py", line 407, in run use_user_site=options.use_user_site, File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\req\__init__.py", line 71, in install_given_reqs **kwargs File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\req\req_install.py", line 811, in install direct_url=direct_url, File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\operations\install\wheel.py", line 630, in install_wheel direct_url=direct_url, File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\operations\install\wheel.py", line 426, in install_unpacked_ wheel console, gui = get_entrypoints(ep_file) File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\operations\install\wheel.py", line 119, in get_entrypoints for line in fp: UnicodeDecodeError: 'gbk' codec can't decode byte 0x97 in position 26: illegal m ultibyte sequence ```
2020-05-28T08:13:14Z
[]
[]
Traceback (most recent call last): File "c:\users\win7_laptop\appdata\local\programs\python\python37\lib\site-pac kages\pip\_internal\cli\base_command.py", line 188, in _main
17,585
pypa/pip
pypa__pip-8553
4bfc54df9bbceda24393405d3360411da90a9f00
diff --git a/src/pip/_internal/locations.py b/src/pip/_internal/locations.py --- a/src/pip/_internal/locations.py +++ b/src/pip/_internal/locations.py @@ -138,7 +138,7 @@ def distutils_scheme( if running_under_virtualenv(): scheme['headers'] = os.path.join( - sys.prefix, + i.prefix, 'include', 'site', 'python{}'.format(get_major_minor_version()),
Unable to install wheel containing .data/headers using from non-writable pip installation into writable --prefix With the following scenario: * pip installed in a virtual environment, not owned by the executing user * ``pip install --prefix`` to a location that *is* owned by the user pip *is* able to install simple wheels, but fails to install wheels with header ``.data`` (didn't check for [other types of data](https://www.python.org/dev/peps/pep-0491/#the-data-directory)) I have confirmed that this is still the case on master with the following Dockerfile (placed in the pip repository root in order to copy the source and install pip): ``` FROM python RUN python -m venv /opt/venv # Install the latest pip (from source) into both the base Python, and the venv we just created. COPY . /tmp/pip-repo RUN python -m pip install /tmp/pip-repo RUN /opt/venv/bin/python -m pip install /tmp/pip-repo RUN useradd -ms /bin/bash not_root USER not_root # Fine RUN /opt/venv/bin/python -m pip install --prefix $HOME/writable wheel # Fine RUN python -m pip install --prefix $HOME/writable pybind11 # Not fine as it attempts to write to {venv}/include/site RUN /opt/venv/bin/python -m pip install --prefix $HOME/writable pybind11 ``` The output of building this Dockerfile with ``docker build --network=host .`` is: ``` $ git rev-parse HEAD 09f9b0030d0a3fe98cfe14e6fd9511100c3155e3 $ docker build --network=host . Sending build context to Docker daemon 517.3MB Step 1/10 : FROM python ---> b55669b4130e Step 2/10 : RUN python -m venv /opt/venv ---> Using cache ---> 12c12f10ec01 Step 3/10 : COPY . /tmp/pip-repo ---> 6a2a8b641e26 Step 4/10 : RUN python -m pip install /tmp/pip-repo ---> Running in 50f5d4a53d52 Processing /tmp/pip-repo Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'done' Building wheels for collected packages: pip Building wheel for pip (PEP 517): started Building wheel for pip (PEP 517): finished with status 'done' Created wheel for pip: filename=pip-20.2.dev1-py2.py3-none-any.whl size=1504387 sha256=c3f4a919e6797f6f477ab912ddc6567f8f7f845b10eb84a09e57b1f6ca612204 Stored in directory: /root/.cache/pip/wheels/77/78/ae/d6e97e1b65b04ed7f7f18819f65a629c406fdfab1661304f08 Successfully built pip Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 20.0.2 Uninstalling pip-20.0.2: Successfully uninstalled pip-20.0.2 Successfully installed pip-20.2.dev1 Removing intermediate container 50f5d4a53d52 ---> 62acdf090a08 Step 5/10 : RUN /opt/venv/bin/python -m pip install /tmp/pip-repo ---> Running in 269e4a89a909 Processing /tmp/pip-repo Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing wheel metadata: started Preparing wheel metadata: finished with status 'done' Building wheels for collected packages: pip Building wheel for pip (PEP 517): started Building wheel for pip (PEP 517): finished with status 'done' Created wheel for pip: filename=pip-20.2.dev1-cp38-none-any.whl size=1504387 sha256=6646a166c762c1b13bf407b81a5c428d1df949fd36b83a5c4f9b02ef43d9616d Stored in directory: /root/.cache/pip/wheels/3a/92/63/e66cd23efd91ab6b7552fc37293c6076634bd7c6e5925abf50 Successfully built pip Installing collected packages: pip Found existing installation: pip 19.2.3 Uninstalling pip-19.2.3: Successfully uninstalled pip-19.2.3 Successfully installed pip-20.2.dev1 Removing intermediate container 269e4a89a909 ---> d2b0273bd03d Step 6/10 : RUN useradd -ms /bin/bash not_root ---> Running in dd9e454eed3d Removing intermediate container dd9e454eed3d ---> e6ea8e7d10c6 Step 7/10 : USER not_root ---> Running in 17075cdc597b Removing intermediate container 17075cdc597b ---> 09dae5d7fe5b Step 8/10 : RUN /opt/venv/bin/python -m pip install --prefix $HOME/writable wheel ---> Running in 252992c43507 Collecting wheel Downloading wheel-0.34.2-py2.py3-none-any.whl (26 kB) Installing collected packages: wheel WARNING: The script wheel is installed in '/home/not_root/writable/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed wheel-0.34.2 Removing intermediate container 252992c43507 ---> 34705392a77b Step 9/10 : RUN python -m pip install --prefix $HOME/writable pybind11 ---> Running in 3d7d6e35d52a Collecting pybind11 Downloading pybind11-2.5.0-py2.py3-none-any.whl (296 kB) Installing collected packages: pybind11 Successfully installed pybind11-2.5.0 Removing intermediate container 3d7d6e35d52a ---> 495db85a9fdb Step 10/10 : RUN /opt/venv/bin/python -m pip install --prefix $HOME/writable pybind11 ---> Running in f0287949ea8f Collecting pybind11 Using cached pybind11-2.5.0-py2.py3-none-any.whl (296 kB) Installing collected packages: pybind11 ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/opt/venv/include/site' Consider using the `--user` option or check the permissions. The command '/bin/sh -c /opt/venv/bin/python -m pip install --prefix $HOME/writable pybind11' returned a non-zero code: 1 ``` The full traceback from this command is: ``` Step 10/10 : RUN /opt/venv/bin/python -m pip -vvv install --prefix $HOME/writable pybind11 ---> Running in fcd054a27042 Non-user install due to --prefix or --target option Created temporary directory: /tmp/pip-ephem-wheel-cache-4jufpvad Created temporary directory: /tmp/pip-req-tracker-4g9cr9c4 Initialized build tracking at /tmp/pip-req-tracker-4g9cr9c4 Created build tracker: /tmp/pip-req-tracker-4g9cr9c4 Entered build tracker: /tmp/pip-req-tracker-4g9cr9c4 Created temporary directory: /tmp/pip-install-c8x570pg 1 location(s) to search for versions of pybind11: * https://pypi.org/simple/pybind11/ Fetching project page and analyzing links: https://pypi.org/simple/pybind11/ Getting page https://pypi.org/simple/pybind11/ Found index url https://pypi.org/simple Looking up "https://pypi.org/simple/pybind11/" in the cache Request header has "max_age" as 0, cache bypassed Starting new HTTPS connection (1): pypi.org:443 https://pypi.org:443 "GET /simple/pybind11/ HTTP/1.1" 304 0 Found link ... snip ... Given no hashes to check 46 links for project 'pybind11': discarding no candidates Using version 2.5.0 (newest of versions: 1.0, 1.2, 1.3, 1.4, 1.5, 1.7, 1.8, 1.8.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 2.2.2, 2.2.3, 2.2.4, 2.3.0, 2.4.0, 2.4.1, 2.4.2, 2.4.3, 2.5.0) Collecting pybind11 Created temporary directory: /tmp/pip-unpack-w_3s0md1 Looking up "https://files.pythonhosted.org/packages/89/e3/d576f6f02bc75bacbc3d42494e8f1d063c95617d86648dba243c2cb3963e/pybind11-2.5.0-py2.py3-none-any.whl" in the cache Current age based on date: 2 Ignoring unknown cache-control directive: immutable Freshness lifetime from max-age: 365000000 The response is "fresh", returning cached response 365000000 > 2 Using cached pybind11-2.5.0-py2.py3-none-any.whl (296 kB) Added pybind11 from https://files.pythonhosted.org/packages/89/e3/d576f6f02bc75bacbc3d42494e8f1d063c95617d86648dba243c2cb3963e/pybind11-2.5.0-py2.py3-none-any.whl#sha256=205d9f9615eac190811cb8c3c2b2f95f6844ddba0fa0a1d45d00793338741601 to build tracker '/tmp/pip-req-tracker-4g9cr9c4' Removed pybind11 from https://files.pythonhosted.org/packages/89/e3/d576f6f02bc75bacbc3d42494e8f1d063c95617d86648dba243c2cb3963e/pybind11-2.5.0-py2.py3-none-any.whl#sha256=205d9f9615eac190811cb8c3c2b2f95f6844ddba0fa0a1d45d00793338741601 from build tracker '/tmp/pip-req-tracker-4g9cr9c4' Installing collected packages: pybind11 Created temporary directory: /tmp/pip-unpacked-wheel-m2gac4cg ERROR: Could not install packages due to an EnvironmentError. Consider using the `--user` option or check the permissions. Traceback (most recent call last): File "/opt/venv/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 393, in run installed = install_given_reqs( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/req/__init__.py", line 71, in install_given_reqs requirement.install( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 819, in install install_wheel( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 683, in install_wheel install_unpacked_wheel( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 497, in install_unpacked_wheel clobber( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 404, in clobber ensure_dir(dest) # common for the 'include' path File "/opt/venv/lib/python3.8/site-packages/pip/_internal/utils/misc.py", line 111, in ensure_dir os.makedirs(path) File "/usr/local/lib/python3.8/os.py", line 213, in makedirs makedirs(head, exist_ok=exist_ok) File "/usr/local/lib/python3.8/os.py", line 213, in makedirs makedirs(head, exist_ok=exist_ok) File "/usr/local/lib/python3.8/os.py", line 223, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/opt/venv/include/site' Removed build tracker: '/tmp/pip-req-tracker-4g9cr9c4' The command '/bin/sh -c /opt/venv/bin/python -m pip -vvv install --prefix $HOME/writable pybind11' returned a non-zero code: 1 ```
From a quick glance, it seems like something in the wheel installation logic does not correctly respect `--prefix`, and wants to install into the “real” scheme of the host Python. I’m guessing similar flags like `--target` may also have the same issue. [Here](https://github.com/pypa/pip/blob/334f06e2248c6114ee4899515c5737845a6a0fcd/src/pip/_internal/locations.py#L141) we unconditionally use `sys.prefix` when calculating the header path when running under virtualenv (or venv). That's definitely not the right thing to do when someone provides `--prefix` explicitly. I don't have a good answer for what we should do, though. The `prefix` argument looks suspecious…
2020-07-07T09:42:12Z
[]
[]
Traceback (most recent call last): File "/opt/venv/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 393, in run installed = install_given_reqs( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/req/__init__.py", line 71, in install_given_reqs requirement.install( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 819, in install install_wheel( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 683, in install_wheel install_unpacked_wheel( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 497, in install_unpacked_wheel clobber( File "/opt/venv/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 404, in clobber ensure_dir(dest) # common for the 'include' path File "/opt/venv/lib/python3.8/site-packages/pip/_internal/utils/misc.py", line 111, in ensure_dir os.makedirs(path) File "/usr/local/lib/python3.8/os.py", line 213, in makedirs makedirs(head, exist_ok=exist_ok) File "/usr/local/lib/python3.8/os.py", line 213, in makedirs makedirs(head, exist_ok=exist_ok) File "/usr/local/lib/python3.8/os.py", line 223, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/opt/venv/include/site'
17,592
pypa/pip
pypa__pip-8656
31299ee37058fafc84535ee3a47f0468433aeb20
diff --git a/src/pip/_internal/operations/install/wheel.py b/src/pip/_internal/operations/install/wheel.py --- a/src/pip/_internal/operations/install/wheel.py +++ b/src/pip/_internal/operations/install/wheel.py @@ -583,8 +583,28 @@ def data_scheme_file_maker(zip_file, scheme): def make_data_scheme_file(record_path): # type: (RecordPath) -> File normed_path = os.path.normpath(record_path) - _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) - scheme_path = scheme_paths[scheme_key] + try: + _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) + except ValueError: + message = ( + "Unexpected file in {}: {!r}. .data directory contents" + " should be named like: '<scheme key>/<path>'." + ).format(wheel_path, record_path) + raise InstallationError(message) + + try: + scheme_path = scheme_paths[scheme_key] + except KeyError: + valid_scheme_keys = ", ".join(sorted(scheme_paths)) + message = ( + "Unknown scheme key used in {}: {} (for file {!r}). .data" + " directory contents should be in subdirectories named" + " with a valid scheme key ({})" + ).format( + wheel_path, scheme_key, record_path, valid_scheme_keys + ) + raise InstallationError(message) + dest_path = os.path.join(scheme_path, dest_subpath) assert_no_path_traversal(scheme_path, dest_path) return ZipBackedFile(record_path, dest_path, zip_file)
pip 20.2 - ValueError exception on improperly formatted package **Environment** * pip version: 20.2 * Python version: 3.6 * OS: Ubuntu 18.04 **Description** `pip install` now fails to install improperly packaged python project. The project has installed a file to 'purelib', rather than under the 'purelib' directory. While the broken project needs to be fixed, pip is now throwing an exception without a hint. This change in behavior is from #8562 (https://github.com/pypa/pip/pull/8562#discussion_r462531471). **Expected behavior** Prior to 20.2, pip install worked fine. The purelib file was not required and was seemingly ignored. **How to Reproduce** Using Ubuntu 18.04: `pip install -v http://archive.ubuntu.com/ubuntu/pool/main/p/python-apt/python-apt_1.6.5ubuntu0.2.tar.xz` **Output** ``` ERROR: Exception: Traceback (most recent call last): File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 216, in _main status = self.run(options, args) File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 182, in wrapper return func(self, options, args) File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 421, in run pycompile=options.compile, File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/req/__init__.py", line 90, in install_given_reqs pycompile=pycompile, File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/req/req_install.py", line 831, in install requested=self.user_supplied, File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/operations/install/wheel.py", line 830, in install_wheel requested=requested, File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/operations/install/wheel.py", line 658, in _install_wheel for file in files: File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/operations/install/wheel.py", line 587, in make_data_scheme_file _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) ValueError: not enough values to unpack (expected 3, got 2) ``` In this case, normed_path is `python_apt-0.0.0.data/purelib`, and points to a file (not a directory).
To add to the reproduction instructions: ``` cd "$(mktemp -d)" python -m venv .env ./.env/bin/python -m pip install --upgrade pip ./.env/bin/python -m pip install wheel sudo apt install libapt-pkg-dev ./.env/bin/python -m pip install -v http://archive.ubuntu.com/ubuntu/pool/main/p/python-apt/python-apt_1.6.5ubuntu0.2.tar.xz ``` which results in ``` ERROR: Exception: Traceback (most recent call last): File "/tmp/user/1000/tmp.wTL19RjBCa/.env/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 216, in _main status = self.run(options, args) File "/tmp/user/1000/tmp.wTL19RjBCa/.env/lib/python3.8/site-packages/pip/_internal/cli/req_command.py", line 182, in wrapper return func(self, options, args) File "/tmp/user/1000/tmp.wTL19RjBCa/.env/lib/python3.8/site-packages/pip/_internal/commands/install.py", line 412, in run installed = install_given_reqs( File "/tmp/user/1000/tmp.wTL19RjBCa/.env/lib/python3.8/site-packages/pip/_internal/req/__init__.py", line 82, in install_given_reqs requirement.install( File "/tmp/user/1000/tmp.wTL19RjBCa/.env/lib/python3.8/site-packages/pip/_internal/req/req_install.py", line 823, in install install_wheel( File "/tmp/user/1000/tmp.wTL19RjBCa/.env/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 821, in install_wheel _install_wheel( File "/tmp/user/1000/tmp.wTL19RjBCa/.env/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 657, in _install_wheel for file in files: File "/tmp/user/1000/tmp.wTL19RjBCa/.env/lib/python3.8/site-packages/pip/_internal/operations/install/wheel.py", line 586, in make_data_scheme_file _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) ValueError: not enough values to unpack (expected 3, got 2) ```
2020-07-29T22:16:05Z
[]
[]
Traceback (most recent call last): File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 216, in _main status = self.run(options, args) File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 182, in wrapper return func(self, options, args) File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 421, in run pycompile=options.compile, File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/req/__init__.py", line 90, in install_given_reqs pycompile=pycompile, File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/req/req_install.py", line 831, in install requested=self.user_supplied, File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/operations/install/wheel.py", line 830, in install_wheel requested=requested, File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/operations/install/wheel.py", line 658, in _install_wheel for file in files: File "/tmp/venv/lib/python3.6/site-packages/pip/_internal/operations/install/wheel.py", line 587, in make_data_scheme_file _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2) ValueError: not enough values to unpack (expected 3, got 2)
17,600
pypa/pip
pypa__pip-8666
5bfd1db071c78c4bdcf2e80cc2142f1557d17d25
diff --git a/src/pip/_internal/utils/misc.py b/src/pip/_internal/utils/misc.py --- a/src/pip/_internal/utils/misc.py +++ b/src/pip/_internal/utils/misc.py @@ -137,7 +137,7 @@ def get_prog(): # Retry every half second for up to 3 seconds @retry(stop_max_delay=3000, wait_fixed=500) def rmtree(dir, ignore_errors=False): - # type: (Text, bool) -> None + # type: (AnyStr, bool) -> None shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler) diff --git a/src/pip/_internal/utils/temp_dir.py b/src/pip/_internal/utils/temp_dir.py --- a/src/pip/_internal/utils/temp_dir.py +++ b/src/pip/_internal/utils/temp_dir.py @@ -10,6 +10,7 @@ from pip._vendor.contextlib2 import ExitStack from pip._vendor.six import ensure_text +from pip._internal.utils.compat import WINDOWS from pip._internal.utils.misc import enum, rmtree from pip._internal.utils.typing import MYPY_CHECK_RUNNING @@ -193,10 +194,17 @@ def cleanup(self): """Remove the temporary directory created and reset state """ self._deleted = True - if os.path.exists(self._path): - # Make sure to pass unicode on Python 2 to make the contents also - # use unicode, ensuring non-ASCII names and can be represented. + if not os.path.exists(self._path): + return + # Make sure to pass unicode on Python 2 to make the contents also + # use unicode, ensuring non-ASCII names and can be represented. + # This is only done on Windows because POSIX platforms use bytes + # natively for paths, and the bytes-text conversion omission avoids + # errors caused by the environment configuring encodings incorrectly. + if WINDOWS: rmtree(ensure_text(self._path)) + else: + rmtree(self._path) class AdjacentTempDirectory(TempDirectory):
Pip 20.2 causes UnicodeDecodeError <!-- If you're reporting an issue for `--unstable-feature=resolver`, use the "Dependency resolver failures / errors" template instead. --> **Environment** * pip version: 20.2 * Python version: 2.7.5 * OS: CentOS 7.8.2003 <!-- Feel free to add more information about your environment here --> **Description** Installing some(?) packages fails with a `UnicodeDecodeError` exception. **Expected behavior** I expect the packages to be installed successfully like it does with 20.1 **How to Reproduce** Build the following Dockerfile: ```dockerfile FROM centos:7 RUN yum -y install python-virtualenv RUN virtualenv --python=python2 env RUN ./env/bin/pip install -U pip==20.2 setuptools==44.1.1 wheel==0.34.2 RUN ./env/bin/pip install ansible==2.7.9 ``` ```console $ docker build -t pip-bug . ``` **Output** ```console $ docker build -t pip-bug . Sending build context to Docker daemon 2.048kB Step 1/5 : FROM centos:7 ---> b5b4d78bc90c Step 2/5 : RUN yum -y install python-virtualenv ---> Using cache ---> 809b2152d1a1 Step 3/5 : RUN virtualenv --python=python2 env ---> Using cache ---> 69dd1f9b3061 Step 4/5 : RUN ./env/bin/pip install -U pip==20.2 setuptools==44.1.1 wheel==0.34.2 ---> Using cache ---> 4cfb8184c74b Step 5/5 : RUN ./env/bin/pip install ansible==2.7.9 ---> Running in bc33d8f35d95 DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Collecting ansible==2.7.9 Downloading ansible-2.7.9.tar.gz (11.8 MB) Collecting jinja2 Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB) Collecting PyYAML Downloading PyYAML-5.3.1.tar.gz (269 kB) Collecting paramiko Downloading paramiko-2.7.1-py2.py3-none-any.whl (206 kB) Collecting cryptography Downloading cryptography-3.0-cp27-cp27mu-manylinux2010_x86_64.whl (2.7 MB) Requirement already satisfied: setuptools in /env/lib/python2.7/site-packages (from ansible==2.7.9) (44.1.1) Collecting MarkupSafe>=0.23 Downloading MarkupSafe-1.1.1-cp27-cp27mu-manylinux1_x86_64.whl (24 kB) Collecting pynacl>=1.0.1 Downloading PyNaCl-1.4.0-cp27-cp27mu-manylinux1_x86_64.whl (964 kB) Collecting bcrypt>=3.1.3 Downloading bcrypt-3.1.7-cp27-cp27mu-manylinux1_x86_64.whl (59 kB) Collecting six>=1.4.1 Downloading six-1.15.0-py2.py3-none-any.whl (10 kB) Collecting cffi!=1.11.3,>=1.8 Downloading cffi-1.14.1-cp27-cp27mu-manylinux1_x86_64.whl (388 kB) Collecting ipaddress; python_version < "3" Downloading ipaddress-1.0.23-py2.py3-none-any.whl (18 kB) Collecting enum34; python_version < "3" Downloading enum34-1.1.10-py2-none-any.whl (11 kB) Collecting pycparser Downloading pycparser-2.20-py2.py3-none-any.whl (112 kB) Building wheels for collected packages: ansible, PyYAML Building wheel for ansible (setup.py): started Building wheel for ansible (setup.py): finished with status 'done' Created wheel for ansible: filename=ansible-2.7.9-py2-none-any.whl size=9428759 sha256=9eb07c04d0a932220c25ea55fa20f5d52c10f8fd96914493bc0df59676c21891 Stored in directory: /root/.cache/pip/wheels/bf/17/e3/c01fddfaa1e22530097c1b1933eecd8d1ddf5477f9e588006a Building wheel for PyYAML (setup.py): started Building wheel for PyYAML (setup.py): finished with status 'done' Created wheel for PyYAML: filename=PyYAML-5.3.1-cp27-cp27mu-linux_x86_64.whl size=45644 sha256=c50f35b17810fd226067a47388cdf0ec2decc00389c7cf39f5bbef02755857da Stored in directory: /root/.cache/pip/wheels/d1/d5/a0/3c27cdc8b0209c5fc1385afeee936cf8a71e13d885388b4be2 Successfully built ansible PyYAML Installing collected packages: MarkupSafe, jinja2, PyYAML, six, pycparser, cffi, ipaddress, enum34, cryptography, pynacl, bcrypt, paramiko, ansible Successfully installed MarkupSafe-1.1.1 PyYAML-5.3.1 ansible-2.7.9 bcrypt-3.1.7 cffi-1.14.1 cryptography-3.0 enum34-1.1.10 ipaddress-1.0.23 jinja2-2.11.2 paramiko-2.7.1 pycparser-2.20 pynacl-1.4.0 six-1.15.0 Traceback (most recent call last): File "./env/bin/pip", line 11, in <module> sys.exit(main()) File "/env/lib/python2.7/site-packages/pip/_internal/cli/main.py", line 75, in main return command.main(cmd_args) File "/env/lib/python2.7/site-packages/pip/_internal/cli/base_command.py", line 121, in main return self._main(args) File "/usr/lib64/python2.7/contextlib.py", line 24, in __exit__ self.gen.next() File "/env/lib/python2.7/site-packages/pip/_internal/cli/command_context.py", line 28, in main_context yield File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 479, in __exit__ _reraise_with_existing_context(exc_details) File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 353, in _reraise_with_existing_context exec("raise exc_type, exc_value, exc_tb") File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 468, in __exit__ if cb(*exc_details): File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 396, in _exit_wrapper return cm_exit(cm, *exc_details) File "/usr/lib64/python2.7/contextlib.py", line 24, in __exit__ self.gen.next() File "/env/lib/python2.7/site-packages/pip/_internal/utils/temp_dir.py", line 46, in global_tempdir_manager _tempdir_manager = old_tempdir_manager File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 479, in __exit__ _reraise_with_existing_context(exc_details) File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 353, in _reraise_with_existing_context exec("raise exc_type, exc_value, exc_tb") File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 468, in __exit__ if cb(*exc_details): File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 396, in _exit_wrapper return cm_exit(cm, *exc_details) File "/env/lib/python2.7/site-packages/pip/_internal/utils/temp_dir.py", line 175, in __exit__ self.cleanup() File "/env/lib/python2.7/site-packages/pip/_internal/utils/temp_dir.py", line 199, in cleanup rmtree(ensure_text(self._path)) File "/env/lib/python2.7/site-packages/pip/_vendor/retrying.py", line 49, in wrapped_f return Retrying(*dargs, **dkw).call(f, *args, **kw) File "/env/lib/python2.7/site-packages/pip/_vendor/retrying.py", line 212, in call raise attempt.get() File "/env/lib/python2.7/site-packages/pip/_vendor/retrying.py", line 247, in get six.reraise(self.value[0], self.value[1], self.value[2]) File "/env/lib/python2.7/site-packages/pip/_vendor/retrying.py", line 200, in call attempt = Attempt(fn(*args, **kwargs), attempt_number, False) File "/env/lib/python2.7/site-packages/pip/_internal/utils/misc.py", line 139, in rmtree onerror=rmtree_errorhandler) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 241, in rmtree fullname = os.path.join(path, name) File "/env/lib64/python2.7/posixpath.py", line 80, in join path += '/' + b UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) The command '/bin/sh -c ./env/bin/pip install ansible==2.7.9' returned a non-zero code: 1 ```
What is the `LANG` environment variable in the container? I believe this is related to a change we made to always use Unicode for paths for Windows compatibility. > What is the `LANG` environment variable in the container? I believe this is related to a change we made to always use Unicode for paths for Windows compatibility. ```console $ locale LANG= LC_CTYPE="POSIX" LC_NUMERIC="POSIX" LC_TIME="POSIX" LC_COLLATE="POSIX" LC_MONETARY="POSIX" LC_MESSAGES="POSIX" LC_PAPER="POSIX" LC_NAME="POSIX" LC_ADDRESS="POSIX" LC_TELEPHONE="POSIX" LC_MEASUREMENT="POSIX" LC_IDENTIFICATION="POSIX" LC_ALL= ``` After making the following changes to the Dockerfile, it works. ```diff FROM centos:7 +ENV LANG en_US.utf8 +ENV LC_ALL en_US.utf8 RUN yum -y install python-virtualenv RUN virtualenv --python=python2 env RUN ./env/bin/pip install -U pip==20.2 setuptools==44.1.1 wheel==0.34.2 RUN ./env/bin/pip install ansible==2.7.9 ``` If I understand correctly, this only affects Python 2. If this not the case, please do provide a reproduction case for a newer Python version. :) > If I understand correctly, this only affects Python 2. That's correct. I couldn't reproduce the issue using Python 3.6: ```diff FROM centos:7 -RUN yum -y install python-virtualenv +RUN yum -y install python-virtualenv python3 -RUN virtualenv --python=python2 env +RUN virtualenv --python=python3 env RUN ./env/bin/pip install -U pip==20.2 setuptools==44.1.1 wheel==0.34.2 RUN ./env/bin/pip install ansible==2.7.9 ``` Python 3 always use the text type for paths and handle the encoding correctly. I think the correct fix would be to only call `ensure_text` on Windows.
2020-07-31T00:01:38Z
[]
[]
Traceback (most recent call last): File "./env/bin/pip", line 11, in <module> sys.exit(main()) File "/env/lib/python2.7/site-packages/pip/_internal/cli/main.py", line 75, in main return command.main(cmd_args) File "/env/lib/python2.7/site-packages/pip/_internal/cli/base_command.py", line 121, in main return self._main(args) File "/usr/lib64/python2.7/contextlib.py", line 24, in __exit__ self.gen.next() File "/env/lib/python2.7/site-packages/pip/_internal/cli/command_context.py", line 28, in main_context yield File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 479, in __exit__ _reraise_with_existing_context(exc_details) File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 353, in _reraise_with_existing_context exec("raise exc_type, exc_value, exc_tb") File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 468, in __exit__ if cb(*exc_details): File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 396, in _exit_wrapper return cm_exit(cm, *exc_details) File "/usr/lib64/python2.7/contextlib.py", line 24, in __exit__ self.gen.next() File "/env/lib/python2.7/site-packages/pip/_internal/utils/temp_dir.py", line 46, in global_tempdir_manager _tempdir_manager = old_tempdir_manager File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 479, in __exit__ _reraise_with_existing_context(exc_details) File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 353, in _reraise_with_existing_context exec("raise exc_type, exc_value, exc_tb") File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 468, in __exit__ if cb(*exc_details): File "/env/lib/python2.7/site-packages/pip/_vendor/contextlib2.py", line 396, in _exit_wrapper return cm_exit(cm, *exc_details) File "/env/lib/python2.7/site-packages/pip/_internal/utils/temp_dir.py", line 175, in __exit__ self.cleanup() File "/env/lib/python2.7/site-packages/pip/_internal/utils/temp_dir.py", line 199, in cleanup rmtree(ensure_text(self._path)) File "/env/lib/python2.7/site-packages/pip/_vendor/retrying.py", line 49, in wrapped_f return Retrying(*dargs, **dkw).call(f, *args, **kw) File "/env/lib/python2.7/site-packages/pip/_vendor/retrying.py", line 212, in call raise attempt.get() File "/env/lib/python2.7/site-packages/pip/_vendor/retrying.py", line 247, in get six.reraise(self.value[0], self.value[1], self.value[2]) File "/env/lib/python2.7/site-packages/pip/_vendor/retrying.py", line 200, in call attempt = Attempt(fn(*args, **kwargs), attempt_number, False) File "/env/lib/python2.7/site-packages/pip/_internal/utils/misc.py", line 139, in rmtree onerror=rmtree_errorhandler) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 247, in rmtree rmtree(fullname, ignore_errors, onerror) File "/usr/lib64/python2.7/shutil.py", line 241, in rmtree fullname = os.path.join(path, name) File "/env/lib64/python2.7/posixpath.py", line 80, in join path += '/' + b UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128)
17,602
pypa/pip
pypa__pip-8684
89d8cba55bddfa31ce69d021c79f9997c616f723
diff --git a/src/pip/_internal/operations/install/wheel.py b/src/pip/_internal/operations/install/wheel.py --- a/src/pip/_internal/operations/install/wheel.py +++ b/src/pip/_internal/operations/install/wheel.py @@ -78,6 +78,7 @@ Union, cast, ) + from zipfile import ZipInfo from pip._vendor.pkg_resources import Distribution @@ -420,6 +421,15 @@ def __init__(self, src_record_path, dest_path, zip_file): self._zip_file = zip_file self.changed = False + def _getinfo(self): + # type: () -> ZipInfo + if not PY2: + return self._zip_file.getinfo(self.src_record_path) + # Python 2 does not expose a way to detect a ZIP's encoding, but the + # wheel specification (PEP 427) explicitly mandates that paths should + # use UTF-8, so we assume it is true. + return self._zip_file.getinfo(self.src_record_path.encode("utf-8")) + def save(self): # type: () -> None # directory creation is lazy and after file filtering @@ -439,11 +449,12 @@ def save(self): if os.path.exists(self.dest_path): os.unlink(self.dest_path) - with self._zip_file.open(self.src_record_path) as f: + zipinfo = self._getinfo() + + with self._zip_file.open(zipinfo) as f: with open(self.dest_path, "wb") as dest: shutil.copyfileobj(f, dest) - zipinfo = self._zip_file.getinfo(self.src_record_path) if zip_item_is_executable(zipinfo): set_extracted_file_to_default_mode_plus_executable(self.dest_path)
File encoding issue in _install_wheel (pip 20.2, python 2) **Environment** * pip version: 20.2 * Python version: 2.7 * OS: linux **Description** `pip install mr.bob` fails with pip 20.2: ``` Processing /home/sbi-local/.cache/pip/wheels/d3/64/58/cd7b9ff05f450397981fa37a0a279ed1d12cf763af16d8d7d7/mr.bob-0.1.2-py2-none-any.whl Requirement already satisfied: Jinja2>=2.5.0 in /home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages (from mr.bob) (2.11.2) Requirement already satisfied: six>=1.2.0 in /home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages (from mr.bob) (1.15.0) Requirement already satisfied: setuptools in /home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages (from mr.bob) (44.1.1) Requirement already satisfied: MarkupSafe>=0.23 in /home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages (from Jinja2>=2.5.0->mr.bob) (1.1.1) Installing collected packages: mr.bob ERROR: Exception: Traceback (most recent call last): File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/cli/base_command.py", line 216, in _main status = self.run(options, args) File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/cli/req_command.py", line 182, in wrapper return func(self, options, args) File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/commands/install.py", line 421, in run pycompile=options.compile, File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/req/__init__.py", line 90, in install_given_reqs pycompile=pycompile, File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 831, in install requested=self.user_supplied, File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/operations/install/wheel.py", line 829, in install_wheel requested=requested, File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/operations/install/wheel.py", line 658, in _install_wheel file.save() File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/operations/install/wheel.py", line 442, in save with self._zip_file.open(self.src_record_path) as f: File "/usr/lib/python2.7/zipfile.py", line 984, in open zinfo = self.getinfo(name) File "/usr/lib/python2.7/zipfile.py", line 932, in getinfo 'There is no item named %r in the archive' % name) KeyError: "There is no item named u'mrbob/tests/templates/encodingc\\u030c/mapc\\u030ca/c\\u0301a.bob' in the archive" ``` I've not had time to investigate if that error comes from a bug in that old package or is a bug in the new `_install_wheel`. It works fine with pip 20.1 though, as well as with pip 20.2 on python 3.
cc/ @chrahunt This looks like a regression in 20.2, so I'm tentatively adding it to the 20.2.1 milestone. Encoding `src_record_path` in utf-8 before calling zipfile [open](https://github.com/pypa/pip/blob/e51a027964b524cccd7b3fe530dd59f87edc7d8f/src/pip/_internal/operations/install/wheel.py#L442) and [getinfo](https://github.com/pypa/pip/blob/e51a027964b524cccd7b3fe530dd59f87edc7d8f/src/pip/_internal/operations/install/wheel.py#L446) seems to fix the issue, although I'm not sure it's the right approach. @chrahunt @uranusjr do you have an advice about this? This sounds like a hairy topic. Quoting Python 2 documentation on `zipfile`: > There is no official file name encoding for ZIP files. If you have unicode file names, you must convert them to byte strings in your desired encoding before passing them to `write()`. WinZip interprets all file names as encoded in CP437, also known as DOS Latin. So I guess there is no “correct” way here. Python 3 [detects UTF-8 support with a header flag](https://github.com/python/cpython/blob/3.8/Lib/zipfile.py#L1549-L1553). I’m not familiar with the ZIP spec to comment on the approach, and would assume it’s the best we can do. I posted #8684 for this.
2020-08-02T22:41:52Z
[]
[]
Traceback (most recent call last): File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/cli/base_command.py", line 216, in _main status = self.run(options, args) File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/cli/req_command.py", line 182, in wrapper return func(self, options, args) File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/commands/install.py", line 421, in run pycompile=options.compile, File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/req/__init__.py", line 90, in install_given_reqs pycompile=pycompile, File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 831, in install requested=self.user_supplied, File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/operations/install/wheel.py", line 829, in install_wheel requested=requested, File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/operations/install/wheel.py", line 658, in _install_wheel file.save() File "/home/sbi-local/.virtualenvs/tempenv-7d78147760d35/lib/python2.7/site-packages/pip/_internal/operations/install/wheel.py", line 442, in save with self._zip_file.open(self.src_record_path) as f: File "/usr/lib/python2.7/zipfile.py", line 984, in open zinfo = self.getinfo(name) File "/usr/lib/python2.7/zipfile.py", line 932, in getinfo 'There is no item named %r in the archive' % name) KeyError: "There is no item named u'mrbob/tests/templates/encodingc\\u030c/mapc\\u030ca/c\\u0301a.bob' in the archive"
17,605
pypa/pip
pypa__pip-9055
ea74bd3d9085234601a0a6199b2ad65c6b6a002f
diff --git a/src/pip/_internal/resolution/resolvelib/resolver.py b/src/pip/_internal/resolution/resolvelib/resolver.py --- a/src/pip/_internal/resolution/resolvelib/resolver.py +++ b/src/pip/_internal/resolution/resolvelib/resolver.py @@ -180,7 +180,10 @@ def get_installation_order(self, req_set): assert self._result is not None, "must call resolve() first" graph = self._result.graph - weights = get_topological_weights(graph) + weights = get_topological_weights( + graph, + expected_node_count=len(self._result.mapping) + 1, + ) sorted_items = sorted( req_set.requirements.items(), @@ -190,8 +193,8 @@ def get_installation_order(self, req_set): return [ireq for _, ireq in sorted_items] -def get_topological_weights(graph): - # type: (Graph) -> Dict[Optional[str], int] +def get_topological_weights(graph, expected_node_count): + # type: (Graph, int) -> Dict[Optional[str], int] """Assign weights to each node based on how "deep" they are. This implementation may change at any point in the future without prior @@ -231,7 +234,7 @@ def visit(node): # Sanity checks assert weights[None] == 0 - assert len(weights) == len(graph) + assert len(weights) == expected_node_count return weights
2020 resolver: get_topological_weights AssertionError **What did you want to do?** ``` pip install --use-feature 2020-resolver sphinx==1.8.5 pip install --use-feature 2020-resolver sphinx sphinxcontrib-bibtex ``` After installing sphinx 1.8.5, pip freeze gives this: ``` alabaster==0.7.12 Babel==2.8.0 certifi==2020.6.20 chardet==3.0.4 docutils==0.16 idna==2.10 imagesize==1.2.0 Jinja2==2.11.2 MarkupSafe==1.1.1 packaging==20.4 Pygments==2.7.1 pyparsing==2.4.7 pytz==2020.1 requests==2.24.0 six==1.15.0 snowballstemmer==2.0.0 Sphinx==1.8.5 sphinxcontrib-serializinghtml==1.1.4 sphinxcontrib-websupport==1.2.4 urllib3==1.25.11 ``` **Output** ``` ERROR: Exception: Traceback (most recent call last): File "/home/jahn/usr/src/pipmaster/src/pip/_internal/cli/base_command.py", line 222, in _main status = self.run(options, args) File "/home/jahn/usr/src/pipmaster/src/pip/_internal/cli/req_command.py", line 178, in wrapper return func(self, options, args) File "/home/jahn/usr/src/pipmaster/src/pip/_internal/commands/install.py", line 378, in run requirement_set File "/home/jahn/usr/src/pipmaster/src/pip/_internal/resolution/resolvelib/resolver.py", line 183, in get_installation_order weights = get_topological_weights(graph) File "/home/jahn/usr/src/pipmaster/src/pip/_internal/resolution/resolvelib/resolver.py", line 242, in get_topological_weights assert len(weights) == len(graph) AssertionError ``` **Additional information** Dependency tree (before error): ``` pipdeptree==1.0.0 - pip [required: >=6.0.0, installed: 20.3.dev0] Sphinx==1.8.5 - alabaster [required: >=0.7,<0.8, installed: 0.7.12] - babel [required: >=1.3,!=2.0, installed: 2.8.0] - pytz [required: >=2015.7, installed: 2020.1] - docutils [required: >=0.11, installed: 0.16] - imagesize [required: Any, installed: 1.2.0] - Jinja2 [required: >=2.3, installed: 2.11.2] - MarkupSafe [required: >=0.23, installed: 1.1.1] - packaging [required: Any, installed: 20.4] - pyparsing [required: >=2.0.2, installed: 2.4.7] - six [required: Any, installed: 1.15.0] - Pygments [required: >=2.0, installed: 2.7.1] - requests [required: >=2.0.0, installed: 2.24.0] - certifi [required: >=2017.4.17, installed: 2020.6.20] - chardet [required: >=3.0.2,<4, installed: 3.0.4] - idna [required: >=2.5,<3, installed: 2.10] - urllib3 [required: >=1.21.1,<1.26,!=1.25.1,!=1.25.0, installed: 1.25.11] - setuptools [required: Any, installed: 41.6.0] - six [required: >=1.5, installed: 1.15.0] - snowballstemmer [required: >=1.1, installed: 2.0.0] - sphinxcontrib-websupport [required: Any, installed: 1.2.4] - sphinxcontrib-serializinghtml [required: Any, installed: 1.1.4] ``` When installing sphinx and sphixcontrib-bibtex, sphinx is set to upgrade to 3.2.1. The error only appears when sphinx is given on the command line. When only sphinxcontrib-bibtex is installed, it works fine and sphinx is upgraded. The error appears both in 20.2.4 and master. This is the value of `weights` in get_topological_weights: ``` {'six': 5, '<Python from Requires-Python>': 5, 'latexcodec': 4, 'pyyaml': 4, 'pybtex': 3, 'setuptools': 3, 'oset': 2, 'docutils': 3, 'pybtex-docutils': 2, 'pyparsing': 4, 'packaging': 3, 'pygments': 3, 'alabaster': 3, 'sphinxcontrib-devhelp': 3, 'sphinxcontrib-jsmath': 3, 'sphinxcontrib-serializinghtml': 3, 'markupsafe': 4, 'jinja2': 3, 'snowballstemmer': 3, 'sphinxcontrib-applehelp': 3, 'sphinxcontrib-htmlhelp': 3, 'idna': 4, 'chardet': 4, 'urllib3': 4, 'certifi': 4, 'requests': 3, 'pytz': 4, 'babel': 3, 'imagesize': 3, 'sphinxcontrib-qthelp': 3, 'sphinx': 2, 'sphinxcontrib-bibtex': 1, None: 0} ``` This is `graph`: ``` <pip._vendor.resolvelib.structs.DirectedGraph object at 0x7f99ccef19d0> ``` This is `graph._vertices`: ``` {'<Python from Requires-Python>', 'oset', None, 'idna', 'sphinxcontrib-devhelp', 'sphinxcontrib-jsmath', 'urllib3', 'sphinxcontrib-htmlhelp', 'six', 'imagesize', 'pyyaml', 'snowballstemmer', 'certifi', 'sphinxcontrib-qthelp', 'markupsafe', 'docutils', 'packaging', 'sphinxcontrib-bibtex', 'sphinx', 'pytz', 'alabaster', 'pyparsing', 'jinja2', 'sphinxcontrib-applehelp', 'babel', 'pygments', 'pybtex-docutils', 'setuptools', 'sphinxcontrib-websupport', 'sphinxcontrib-serializinghtml', 'pybtex', 'requests', 'latexcodec', 'chardet'} ``` sphinxcontrib-websupport is missing from weights. This is `graph._forwards`: ``` {None: {'sphinxcontrib-bibtex', 'sphinx'}, 'sphinx': {'docutils', 'packaging', '<Python from Requires-Python>', 'pygments', 'setuptools', 'alabaster', 'sphinxcontrib-devhelp', 'sphinxcontrib-jsmath', 'sphinxcontrib-serializinghtml', 'jinja2', 'snowballstemmer', 'sphinxcontrib-applehelp', 'sphinxcontrib-htmlhelp', 'requests', 'babel', 'imagesize', 'sphinxcontrib-qthelp'}, 'sphinxcontrib-bibtex': {'pybtex', 'oset', 'pybtex-docutils', 'sphinx'}, 'alabaster': set(), 'babel': {'pytz'}, 'six': set(), 'packaging': {'six', 'pyparsing'}, 'pybtex': {'six', 'latexcodec', 'pyyaml', '<Python from Requires-Python>'}, 'pybtex-docutils': {'six', 'docutils', 'pybtex', '<Python from Requires-Python>'}, 'latexcodec': {'six', '<Python from Requires-Python>'}, 'docutils': set(), 'jinja2': {'markupsafe'}, 'imagesize': set(), 'requests': {'idna', 'chardet', 'urllib3', 'certifi'}, 'setuptools': set(), 'oset': {'setuptools'}, 'snowballstemmer': set(), 'pygments': set(), 'sphinxcontrib-jsmath': {'<Python from Requires-Python>'}, 'sphinxcontrib-applehelp': {'<Python from Requires-Python>'}, 'sphinxcontrib-htmlhelp': {'<Python from Requires-Python>'}, 'sphinxcontrib-qthelp': {'<Python from Requires-Python>'}, 'sphinxcontrib-devhelp': {'<Python from Requires-Python>'}, 'sphinxcontrib-serializinghtml': set(), 'sphinxcontrib-websupport': {'sphinxcontrib-serializinghtml'}, '<Python from Requires-Python>': set(), 'pyyaml': {'<Python from Requires-Python>'}, 'pytz': set(), 'markupsafe': set(), 'urllib3': set(), 'certifi': set(), 'chardet': set(), 'idna': set(), 'pyparsing': set()} ``` This is `graph._backwards`: ``` {None: set(), 'sphinx': {'sphinxcontrib-bibtex', None}, 'sphinxcontrib-bibtex': {None}, 'alabaster': {'sphinx'}, 'babel': {'sphinx'}, 'six': {'pybtex', 'packaging', 'latexcodec', 'pybtex-docutils'}, 'packaging': {'sphinx'}, 'pybtex': {'sphinxcontrib-bibtex', 'pybtex-docutils'}, 'pybtex-docutils': {'sphinxcontrib-bibtex'}, 'latexcodec': {'pybtex'}, 'docutils': {'pybtex-docutils', 'sphinx'}, 'jinja2': {'sphinx'}, 'imagesize': {'sphinx'}, 'requests': {'sphinx'}, 'setuptools': {'oset', 'sphinx'}, 'oset': {'sphinxcontrib-bibtex'}, 'snowballstemmer': {'sphinx'}, 'pygments': {'sphinx'}, 'sphinxcontrib-jsmath': {'sphinx'}, 'sphinxcontrib-applehelp': {'sphinx'}, 'sphinxcontrib-htmlhelp': {'sphinx'}, 'sphinxcontrib-qthelp': {'sphinx'}, 'sphinxcontrib-devhelp': {'sphinx'}, 'sphinxcontrib-serializinghtml': {'sphinxcontrib-websupport', 'sphinx'}, 'sphinxcontrib-websupport': set(), '<Python from Requires-Python>': {'pybtex-docutils', 'sphinx', 'sphinxcontrib-devhelp', 'sphinxcontrib-jsmath', 'sphinxcontrib-applehelp', 'pybtex', 'sphinxcontrib-htmlhelp', 'latexcodec', 'pyyaml', 'sphinxcontrib-qthelp'}, 'pyyaml': {'pybtex'}, 'pytz': {'babel'}, 'markupsafe': {'jinja2'}, 'urllib3': {'requests'}, 'certifi': {'requests'}, 'chardet': {'requests'}, 'idna': {'requests'}, 'pyparsing': {'packaging'}} ```
This is causing my rtd builds to fail (https://readthedocs.org/projects/dclab/builds/12162768/). My workaround was to pin sphinx to `sphinx<2` in requirements.txt. But this is hardly a good solution. Thanks @jahn for a detailed report here! It has been super helpful to have the reproducer as well as useful debugging information for this issue. --- Visualising the graph here, it looks like we're getting a malformed graph from resolvelib. Graph on 20.2.3 (good): <img width="719" alt="Screenshot 2020-10-23 at 2 59 19 AM" src="https://user-images.githubusercontent.com/3275593/96932021-db071580-14db-11eb-9654-8554f8520cf5.png"> Graph on 20.2.4 (naughty): <img width="719" alt="Screenshot 2020-10-23 at 2 59 51 AM" src="https://user-images.githubusercontent.com/3275593/96932039-e1958d00-14db-11eb-9784-e67f8d9fedb2.png"> Notice how the node for "sphinxcontrib-websupport" has sneaked into this one? That's causing the failure here. --- A quick dump of words to describe things: - sphinx 1.8.5 depends on `sphinxcontrib-websupport`. - the failing install command will try upgrade to a newer sphinx (which doesn't depend on `sphinxcontrib-websupport`) - the lack of --upgrade flag + a forced upgrade + the presence of a "dependency drop" are all needed here. - passing the --upgrade flag makes things work! - this is because the resolver ignores installed versions -> it'll never look at sphinx 1.8.5 -> it won't "see" the `sphinxcontrib-websupport -> sphinxcontrib-serializinghtml` dependency. - the resolver generates the correct result during the resolution and figures out the right details. (yay! or as I said when I figured this out -- thank goodness.) - during the result graph construction, it goes through all packages. - if the node's not in the graph, it adds the parent to the graph. (yes, it does a bunch more but this is what's relevant here) - this bit of logic adds the node that's going to be "orphan" (like `sphinxcontrib-websupport` here) since its "parent" (the older sphinx version) is no longer part of the result (and hence, the graph). - during "figure out the install order", we're constructing a topological order from this graph, under the assumption that all nodes are accessible from the root node. - That assumption is embodied by the assertion here. - Since the assumption is falsified by the behavior in the previous bullet, the assertion fails even though we _technically_ have the correct install order (because it won't visit the `sphinxcontrib-websupport` node during that chunk of code -- only nodes accessible from the root node). :) It seems to me that this issue arises because that we're adding nodes that have no "path to root" in the graph, by adding the parent unconditionally. IOW, this is a bug in resolvelib's `_build_result` function, which means we'd need to fix it there (/cc @uranusjr). --- SOOOO. Possible choices to make here: - Figure out a better approach to generating the graph in resolvelib without orphan nodes like this. - Dropping the assertion, since we know that the topological ordering is working fine and not the cause of this issue. (I like this one -- least effort) - Ignore this issue for 20.3 release, since it's a fairly esoteric edge case. :P Things to do here: 1. pick one of the above. :P 2. figure out a minimal test case for this class of failures. 3. write a test in whichever package we're making the fix on, to ensure this does the right thing. 4. implement the change and get that into master. 5. there is no step 5. --- ```python # This was the blob of code that I used to generate the input to graphviz, for those graphs. print('digraph G {') print(' rankdir=LR;') for node, others in graph._forwards.items(): print(f' "{node}";') for node, others in graph._forwards.items(): for to_node in others: print(f' "{node}" -> "{to_node}";') print('}') ``` /cc @pfmoore because I couldn't find a smooth excuse to mention you earlier than this line. :) I figured that we're only seeing the installed version of `sphinx` because of #8924 and because the user has specified `sphinx` directly. Sooo... dropping sphinx from the set of packages that the user requests would mean that the resolver won't see the already-installed version. And, yes, that works. Yay! ``` pip install --use-feature 2020-resolver sphinx==1.8.5 pip install --use-feature 2020-resolver sphinxcontrib-bibtex ``` Now, it's almost 4am. I'mma sleep. Nice analysis! I think dropping `sphinx` from the list of user-requested packages is a 100% acceptable workaround. It would be nice to not have that node in the graph, but I don't feel that's a critical issue as we know it's not a genuine issue with the resolution or ordering. I'm not 100% clear whether that's possible solely in resolvelib or whether it would need some help from pip, but that's something we can work out. Maybe change the assertion to a warning, so we don't completely lose the information that something odd is going on. And maybe if we can create a test to demonstrate the issue (make it xfail until we deal with it) that would also help us not to forget about it. Brain dump over. Oh, and @jahn can I add my thanks for a very well written, detailed and helpful issue report. It made it much easier to understand what's going on here. > I'm not 100% clear whether that's possible solely in resolvelib or whether it would need some help from pip, but that's something we can work out. This is definitely solvable purely on the resolvelib side -- we'd basically need to rework the graph construction slightly to do the right thing. Can you check whether `sphinxcontrib-websupport` also end up in `mapping`? resolvelib already does cleanup on it, and I’d be very worried if the cleanup is not working. If not, pip should be able to work around this by changing the sanity check to ```python assert len(weights) == len(result.mapping) + 1 # Plus the santinel None node. ``` instead. I will find some time to also fix it on resolvelib’s side as well, assuming the `mapping` entries are correct. Darn, I’m having a hard time trying to come up with an simplified example. It seems that a simple backtrack is not enough to cause the issue. This is what I was trying to use as a test case: ``` * tea-0 depends on kettle==0 * coffee-0 depends on kettle==0 * coffee-1 depends on kettle==1 and water==0 * water-0 depends on nothing * kettle-0 does not depend on anything * kettle-1 depends on non stove==0 which does not exist (causing a backtrack) ``` Now I instruct the resolver to resolve coffee before tea. This would induce backtracking because `kettle-1` ultimately hits a dead end. `water-0` was added for `coffee-1`, and I was expecting it to be left behind after backtracking—but it was not. The resolver correctly cleans it up after resolution, and the graph only contains `coffee-0`, `tea-0`, and `kettle-0`. Not sure what I’m missing 😞 I thought a key point with the original example was that `sphinxcontrib-websupport` was already installed even though we were upgrading to a version of `sphinx` that didn't depend on it? Would that show up differently in the resolvelib data? It would mean that the older version of `sphinx` that depended on `sphinx-webcontrib` gets prioritised (and seen by the resolver) ahead of the later version that doesn't... I persumed ordering is key as well, which is why I made the *newer* version of `coffee` depend on water, instead of the older. In the original case, and older version of `sphinx` being already installed means that the version is tried before the newer; in my made-up case, the newer `kettle` is tried first. I also tried mimicking the already installed behaviour by swapping `kettle` versions: ``` * tea-0 depends on kettle==0 * coffee-0 depends on kettle==0 * coffee-1 depends on kettle==1 and water==0 * water-0 depends on nothing * kettle-0 depends on non stove==0 which does not exist (causing a backtrack) * kettle-1 does not depend on anything ``` and instruct the provider to put `kettle-0` before `kettle-1` (simulating version 0 being already installed). The behaviour is the same, `water` is not present in the final graph—which is expected, since the resolver does not have any logic regarding the actual version, only how the candidates are ordered; the candidate ordering does not change between my two test cases. ---- Here’s the test code I’m using, maybe it’s me implementing things wrong… ```python def test_result_cleanup(): dependencies = { ("kettle", 0): [], ("kettle", 1): [("stove", {})], ("water", 0): [], ("tea", 0): [("kettle", {0})], ("coffee", 0): [("water", {0}), ("kettle", {1})], ("coffee", 1): [("kettle", {0})], } pref_vers = {"coffee": {0: 1}} # Prefer coffee-0 over coffee-1. class Provider(AbstractProvider): def identify(self, dependency): return dependency[0] def get_preference(self, resolution, candidates, information): # Resolve coffee before tea. This will cause backtracking. if candidates[0][0] == "tea": return 1 return 0 def get_dependencies(self, candidate): return dependencies[candidate] def find_matches(self, requirements): if not requirements: return [] name, versions = requirements.pop() versions = { version for version in versions if all(version in r[1] for r in requirements) } # Prefer coffee-0 over coffee-1. if name == "coffee": return sorted((name, v) for v in versions) return sorted(((name, v) for v in versions), reverse=True) def is_satisfied_by(self, requirement, candidate): return candidate[1] in requirement[1] resolver = Resolver(Provider(), BaseReporter()) result = resolver.resolve([("coffee", {0, 1}), ("tea", {0})]) assert "water" in result.graph, list(result.graph) # AssertionError: [None, 'kettle', 'tea', 'coffee'] ``` Ah I see, sorry. But in the actual example, `sphinxcontrib-websupport` 1.2.4 (the equivalent of your "stove") *does* exist, it's installed in the first run. > pip should be able to work around this by changing the sanity check to > > ```python > assert len(weights) == len(result.mapping) + 1 # Plus the santinel None node. > ``` Yup -- this works. :)
2020-10-26T19:24:50Z
[]
[]
Traceback (most recent call last): File "/home/jahn/usr/src/pipmaster/src/pip/_internal/cli/base_command.py", line 222, in _main status = self.run(options, args) File "/home/jahn/usr/src/pipmaster/src/pip/_internal/cli/req_command.py", line 178, in wrapper return func(self, options, args) File "/home/jahn/usr/src/pipmaster/src/pip/_internal/commands/install.py", line 378, in run requirement_set File "/home/jahn/usr/src/pipmaster/src/pip/_internal/resolution/resolvelib/resolver.py", line 183, in get_installation_order weights = get_topological_weights(graph) File "/home/jahn/usr/src/pipmaster/src/pip/_internal/resolution/resolvelib/resolver.py", line 242, in get_topological_weights assert len(weights) == len(graph) AssertionError
17,621
pypa/pip
pypa__pip-9442
2a3e4f9bfe3da56b6bfbe99628887f44a9852c10
diff --git a/src/pip/_internal/vcs/versioncontrol.py b/src/pip/_internal/vcs/versioncontrol.py --- a/src/pip/_internal/vcs/versioncontrol.py +++ b/src/pip/_internal/vcs/versioncontrol.py @@ -684,6 +684,18 @@ def run_command( raise BadCommand( f'Cannot find command {cls.name!r} - do you have ' f'{cls.name!r} installed and in your PATH?') + except PermissionError: + # errno.EACCES = Permission denied + # This error occurs, for instance, when the command is installed + # only for another user. So, the current user don't have + # permission to call the other user command. + raise BadCommand( + f"No permission to execute {cls.name!r} - install it " + f"locally, globally (ask admin), or check your PATH. " + f"See possible solutions at " + f"https://pip.pypa.io/en/latest/reference/pip_freeze/" + f"#fixing-permission-denied." + ) @classmethod def is_repository_directory(cls, path):
pip freeze returns "Permission denied: 'hg'" after using pip install -e **Environment** * pip version: 19.3.1 and above * Python version: 3.7.7 * OS: macOS 10.14.6 **Description** After using `pip install -e` to install a local package, `pip freeze` returns an error: `PermissionError: [Errno 13] Permission denied: 'hg'`. I do not use Mercurial and do not have an `hg` executable on my machine. It happens with pip 19.3.1 and above, when using `-e`. It doesn't happen with pip 19.2.3, and it doesn't happen if I don't use `-e`. It doesn't happen with `pip list`. **Expected behavior** `pip freeze` should return the list of packages. **How to Reproduce** Create a simple package, install it using `pip install -e`, then run `pip freeze`. It works with pip 19.2.3 but in 19.3.1 or later versions, `pip freeze` returns an error. You can just copy/paste the following, which creates a virtual environment and does the `pip install -e` and the `pip freeze` on two different versions of pip: ``` cd mkdir testdir cd testdir/ virtualenv testenv source testenv/bin/activate mkdir my_plugin echo " from setuptools import setup setup( name='my_plugin', py_modules=['my_plugin'], version='1.0.0', ) " > my_plugin/setup.py pip install pip==19.2.3 pip -V pip install -e my_plugin/ pip freeze pip uninstall -y my_plugin pip freeze pip install pip==19.3.1 pip -V pip install -e my_plugin/ pip freeze pip uninstall -y my_plugin pip freeze ``` **Output** Here's the output of the above commands, starting at the first `pip -V`: ``` $ pip -V pip 19.2.3 from /Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip (python 3.7) $ pip install -e my_plugin/ Obtaining file:///Users/<username>/testdir/my_plugin Installing collected packages: my-plugin Running setup.py develop for my-plugin Successfully installed my-plugin WARNING: You are using pip version 19.2.3, however version 20.2b1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. $ pip freeze # Editable install with no version control (my-plugin==1.0.0) -e /Users/<username>/testdir/my_plugin $ pip uninstall -y my_plugin Uninstalling my-plugin-1.0.0: Successfully uninstalled my-plugin-1.0.0 $ pip freeze $ pip install pip==19.3.1 Collecting pip==19.3.1 Using cached https://files.pythonhosted.org/packages/00/b6/9cfa56b4081ad13874b0c6f96af8ce16cfbc1cb06bedf8e9164ce5551ec1/pip-19.3.1-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 19.2.3 Uninstalling pip-19.2.3: Successfully uninstalled pip-19.2.3 Successfully installed pip-19.3.1 $ pip -V pip 19.3.1 from /Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip (python 3.7) $ pip install -e my_plugin/ Obtaining file:///Users/<username>/testdir/my_plugin Installing collected packages: my-plugin Running setup.py develop for my-plugin Successfully installed my-plugin WARNING: You are using pip version 19.3.1; however, version 20.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. $ pip freeze ERROR: Exception: Traceback (most recent call last): File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 153, in _main status = self.run(options, args) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/commands/freeze.py", line 100, in run for line in freeze(**freeze_kwargs): File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/operations/freeze.py", line 70, in freeze req = FrozenRequirement.from_dist(dist) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/operations/freeze.py", line 249, in from_dist req, editable, comments = get_requirement_info(dist) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/operations/freeze.py", line 188, in get_requirement_info vcs_backend = vcs.get_backend_for_dir(location) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py", line 234, in get_backend_for_dir if vcs_backend.controls_location(location): File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/vcs/mercurial.py", line 149, in controls_location log_failed_cmd=False) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py", line 632, in run_command log_failed_cmd=log_failed_cmd) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/utils/subprocess.py", line 190, in call_subprocess stdout=subprocess.PIPE, cwd=cwd, env=env, File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 800, in __init__ restore_signals, start_new_session) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) PermissionError: [Errno 13] Permission denied: 'hg' $ pip uninstall -y my_plugin Uninstalling my-plugin-1.0.0: Successfully uninstalled my-plugin-1.0.0 $ pip freeze $ ``` `pip list` still works. In fact, if I add `pip list` just before the problematic `pip freeze` in the chain of commands above, there is no error: ``` $ pip list Package Version ---------- ------- my-plugin 1.0.0 pip 19.3.1 setuptools 47.1.1 wheel 0.34.2 WARNING: You are using pip version 19.3.1; however, version 20.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. $ pip freeze my-plugin==1.0.0 ```
Is `my_plugin` managed by mercurial, and does your project root contain a `.hg` directory? I suspect this is a side effect of #7065; the Mercurial detection code path is much less trotted than Git due to popularity, and this may be hitting an edge case where Mercurial is expected but not actually being available. What does it show if you run `hg` in the command line? So I don't have `hg` at all: ``` $ hg -bash: hg: command not found $ type hg -bash: type: hg: not found ``` In my repro steps, there is no `.hg`folder, either in `~/testdir/` or in `~`. I'm not sure what makes pip expect to find Mercurial. Oh, I also found #7072. It's about Mercurial and pip freeze and was merged between 19.2.3 and 19.3.1, so it seems likely that the problem started there. I'll look more. It’d be awesome if you could `git bisect` the exact commit that introduced the breakage. This is quite difficult to reproduce locally 😢 I'd never heard of that tool! This is awesome. I'm running it between [a5b1a57](https://github.com/pypa/pip/commit/a5b1a57d6707ca9a8ea28c3c1d96b266ed88fbcb) (19.2.3) and [a5b1a57](https://github.com/pypa/pip/commit/6500e595601b8cb4ce597b9f7a71aaf82441c1f8) (19.3.1), which I know as good and bad respectively. This is the result: ``` c0809f4183cbf40e3fd69245095537456d74b97f is the first bad commit commit c0809f4183cbf40e3fd69245095537456d74b97f Author: Tony Beswick <tonybeswick@orcon.net.nz> Date: Tue Sep 24 11:46:02 2019 +1200 Added a `controls_location` implementation to the `Mercurial` class, so it porperly detects that subdirectories are under mercurial control. :040000 040000 6a58155df7ff4b3457d40c849c2c4f659df01db6 3d487b2c2fb13982d89e0291b91b964d9be8416a M src ``` It points to commit [c0809f4](https://github.com/pypa/pip/commit/c0809f4183cbf40e3fd69245095537456d74b97f). I'm not sure why this code would run since I don't have Mercurial. But it makes sense to me that if pip is trying to run that code, then the `cls.run_command()` fails. I think I'll need to dig into why pip thinks it needs to run code for Mercurial. Another interesting thing is that the implementation does try to catch the error when hg is not installed (the `BadCommand` block) but your environment raises something it does not expect. I wonder why your system raises `PermissionError` instead of `FileNotFoundError`, which is the expected exception for unavailable commands. Yes that's really odd. I'll do my best to track this down and understand what's wrong with my environment and see if pip can detect that. Thanks for your help so far! Is there anything actionable here? I'm sorry but I can't tell. I'm experiencing the same problem with my project. @uranusjr were you able to resolve this? I noticed that an egg was being made with a different name than my source code, due to an uneditted setup.py Removing the egg allowed pip freeze to run properly. I haven't taken the time to figure out why my environment behaves in this way. I still have the problem but am still working around it by pinning pip to an earlier version. I'm okay closing the ticket for now (if that's what you're asking), if I can reopen it when I have more information about the problem. I encountered this issue recently. I worked around the issue by downgrading pip to 19.2.3. It may make sense if we just treat `PermissionError` the same as `FileNotFoundError` in the version control code. The two exceptions both signal that the version control tool is not available, which is what we really care about, after all. Another choice would be to perform our own command resolution logic (via `shutil.which()`) instead of relying the operating system to emit a `FileNotFoundError` for the subprocess. But I’m not quite sure if that’s feasible for pip right now (because Python 2). I had the same issue, pip-20.2.4 ``` $ pip freeze ERROR: Exception: Traceback (most recent call last): File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 228, in _main status = self.run(options, args) File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/commands/freeze.py", line 101, in run for line in freeze(**freeze_kwargs): File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/operations/freeze.py", line 67, in freeze req = FrozenRequirement.from_dist(dist) File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/operations/freeze.py", line 252, in from_dist req, editable, comments = get_requirement_info(dist) File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/operations/freeze.py", line 187, in get_requirement_info vcs_backend = vcs.get_backend_for_dir(location) File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/vcs/versioncontrol.py", line 333, in get_backend_for_dir repo_path = vcs_backend.get_repository_root(location) File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/vcs/mercurial.py", line 147, in get_repository_root log_failed_cmd=False, File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/vcs/versioncontrol.py", line 774, in run_command log_failed_cmd=log_failed_cmd) File "/home/ec2-user/st-prod/lib/python3.6/site-packages/pip/_internal/vcs/versioncontrol.py", line 119, in call_subprocess cwd=cwd File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__ restore_signals, start_new_session) File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) PermissionError: [Errno 13] Permission denied: 'hg' ``` I had to install hg-git to fix it `sudo yum install hg-git -y` I’m even more confused to hear your fix worked. What on earth is going on. Hi, I am having the same issue with `pip freeze` on the following configuration: **Environment** - Pip version: 20.3.1 (2020-12-03) - Python version: 2.7.6 - OS: macOS 10.14.6 **Diagnostic** I have two user profiles for development (named "first" and "second" here). On the first profile, `pip` works without problem; on the second profile, I have the issue: when I run `hg` on the command line, I get: ```shell second@imac-de-laurent-1 ~> hg fish: Unknown command 'hg' ``` So, I took a look on the first profile, it appears that `hg` works! ```shell first@imac-de-laurent-1 ~> hg Mercurial Distributed SCM […] ``` The problem is that the `hg` command in a symbolic link to a **user-level** installation of [SourceTree](https://www.sourcetreeapp.com/): ```shell second@iMac-de-Laurent ~> ls -l /usr/local/bin/hg lrwxr-xr-x 1 first admin 93 13 oct 2016 /usr/local/bin/hg -> /Users/first/Applications/SourceTree.app/Contents/Resources/mercurial_local/hg_local ``` So, if I launch this command from the second profile, I get a "permission denied" error: ```shell second@iMac-de-Laurent ~> /usr/local/bin/hg second@iMac-de-Laurent ~ [126]> ``` => exit code is 126 **How to fix?** From the Pip's point of view, the `hg` command should be considered unavailable. So you should take into account that Permission denied `[Errno 13]` is a valid exception, and should catch it. But, it could be useful for the user (the developer) to emit a warning and alert him that he doesn't have access to this tool even if it is installed. In my situation, I will try to uninstall SourceTree and reinstall it "globally". Once SourceTree uninstalled (and the broken symbolic link removed), I tried `pip freeze` again. This time, I get: ```shell second@imac-de-laurent-1 ~/w/my_project(262|M?)> pip freeze --verbose Created temporary directory: /private/var/folders/lr/hjtkqzxd189dw_x7dk0493h80000gp/T/pip-ephem-wheel-cache-9hFWsh Checking in /Users/second/workspace/my_project/src for .svn (svn)... Checking in /Users/second/workspace/my_project/src for .git (git)... Checking in /Users/second/workspace/my_project/src for .bzr (bzr)... Checking in /Users/second/workspace/my_project/src for .hg (hg)... could not determine if /Users/second/workspace/my_project/src is under hg control because hg is not available No VCS found for editable requirement "my_project==3.1.26" in: '/Users/second/workspace/my_project/src' ... [list of dependencies] ``` It's curious because my project is under Subversion, so the checking of `.svn` should have worked. Is it another problem? > rom the Pip's point of view, the `hg` command should be considered unavailable. This is arguably a user issue because `hg` *is* available, but corrupted. pip can definitely catch `PermissionError` and emit a better error message, but probably should not pretend the command does not exist at all. I’ll mark this as “awaiting PR” since it is pretty clear what we want to do. Feel free to try your hands on this and we can continue the discussion from there! OK @uranusjr , I'm working on it. I will use an error message suggesting the developper to reinstall the 'hg' (or whatever) tool for all users (globally). For instance: "Command hg is available, but you don't have permission to execute it - Can you ask an admin to reinstall hg for all users?"
2021-01-11T08:30:54Z
[]
[]
Traceback (most recent call last): File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 153, in _main status = self.run(options, args) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/commands/freeze.py", line 100, in run for line in freeze(**freeze_kwargs): File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/operations/freeze.py", line 70, in freeze req = FrozenRequirement.from_dist(dist) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/operations/freeze.py", line 249, in from_dist req, editable, comments = get_requirement_info(dist) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/operations/freeze.py", line 188, in get_requirement_info vcs_backend = vcs.get_backend_for_dir(location) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py", line 234, in get_backend_for_dir if vcs_backend.controls_location(location): File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/vcs/mercurial.py", line 149, in controls_location log_failed_cmd=False) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py", line 632, in run_command log_failed_cmd=log_failed_cmd) File "/Users/<username>/testdir/testenv/lib/python3.7/site-packages/pip/_internal/utils/subprocess.py", line 190, in call_subprocess stdout=subprocess.PIPE, cwd=cwd, env=env, File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 800, in __init__ restore_signals, start_new_session) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) PermissionError: [Errno 13] Permission denied: 'hg'
17,650
pypa/pip
pypa__pip-9467
3af9093a73c8629369f57d98a1d3fff9bc7b1f47
diff --git a/src/pip/_internal/req/req_install.py b/src/pip/_internal/req/req_install.py --- a/src/pip/_internal/req/req_install.py +++ b/src/pip/_internal/req/req_install.py @@ -432,8 +432,16 @@ def check_if_exists(self, use_user_site): if not existing_dist: return - existing_version = existing_dist.parsed_version - if not self.req.specifier.contains(existing_version, prereleases=True): + # pkg_resouces may contain a different copy of packaging.version from + # pip in if the downstream distributor does a poor job debundling pip. + # We avoid existing_dist.parsed_version and let SpecifierSet.contains + # parses the version instead. + existing_version = existing_dist.version + version_compatible = ( + existing_version is not None and + self.req.specifier.contains(existing_version, prereleases=True) + ) + if not version_compatible: self.satisfied_by = None if use_user_site: if dist_in_usersite(existing_dist):
Arch with python-pip: TypeError: expected string or bytes-like object As soon as I've upgraded Python from 3.8 to 3.9 on Arch Linux I noticed a strange behaviour with all packages that depend on `setuptools`. What I'll decribe below does NOT happen with Python 3.8 and these packages nor with Python 3.9 and packages that do not depend on `setuptools`. This is shy I'm reporting this issue here. 1. Have a fresh Python 3.9 installation with no `--user` packages, meaning `~/.local/bin`, `~/.local/lib` and `~/.local/include` are all empty 2. Install a package that does not depend on `setuptools`, for example `pip install --user vim-vint` - installs OK 3. Install the same or any other package that that does not depend on `setuptools` - installs OK 4. Install any package that depends on setuptools, for example `pip install --user locust` - installs OK 5. Try installing any package now - always fails with the following error ``` ERROR: Exception: Traceback (most recent call last): File "/usr/lib/python3.9/site-packages/pip/_internal/cli/base_command.py", line 216, in _main status = self.run(options, args) File "/usr/lib/python3.9/site-packages/pip/_internal/cli/req_command.py", line 182, in wrapper return func(self, options, args) File "/usr/lib/python3.9/site-packages/pip/_internal/commands/install.py", line 324, in run requirement_set = resolver.resolve( File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 183, in resolve discovered_reqs.extend(self._resolve_one(requirement_set, req)) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 388, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 331, in _get_abstract_dist_for skip_reason = self._check_skip_installed(req) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 236, in _check_skip_installed req_to_install.check_if_exists(self.use_user_site) File "/usr/lib/python3.9/site-packages/pip/_internal/req/req_install.py", line 437, in check_if_exists if not self.req.specifier.contains(existing_version, prereleases=True): File "/usr/lib/python3.9/site-packages/packaging/specifiers.py", line 790, in contains item = parse(item) File "/usr/lib/python3.9/site-packages/packaging/version.py", line 57, in parse return Version(version) File "/usr/lib/python3.9/site-packages/packaging/version.py", line 296, in __init__ match = self._regex.search(version) TypeError: expected string or bytes-like object ``` At this point you are unable to use `pip install` because it will always give the above error. Observation: even though `setuptools` was originally installed in `/usr/lib/python3.9/site-packages/`, after we've installed a package that depends on `setuptools` it was also put in `~/.local/lib/python3.9/site-packages/`.
I attempted to replicate the issue you described with this Dockerfile but was unsuccessful: ``` FROM archlinux RUN pacman -Sy python-pip --noconfirm RUN pip install --user zope.interface RUN pip install pipx ``` The `install zope.interface` line shows this output: ``` Collecting zope.interface Downloading zope.interface-5.2.0-cp39-cp39-manylinux2010_x86_64.whl (241 kB) Requirement already satisfied: setuptools in /usr/lib/python3.9/site-packages (from zope.interface) (51.0.0) Installing collected packages: zope.interface Successfully installed zope.interface-5.2.0 ``` Note, `locust` doesn't depend on setuptools directly, but does indirectly through `zope.interface` (and others), so I've used `zope.interface` in place of locust for faster resolution. Can you help produce a Dockerfile that replicates the undesirable behavior? Thanks for looking into it! In fact, and I previously did not think this was important, I'm using `--force-reinstall` param to perform an update of already installd packages. This param seems to be the culprit here. ``` FROM archlinux RUN pacman -Sy --noconfirm RUN pacman -S --noconfirm python python-pip RUN pip install --user zope.interface RUN pip install --user zope.interface RUN pip install --user --force-reinstall zope.interface RUN pip install --user zope.interface ``` Although `setuptools` is installed globally in `/usr/lib/python3.9/site-packages/`, as soon as I install anything using `--force-reinstall`, `setuptools` gets installed locally into `~/.local/lib/python3.9/site-packages/` and the whole `pip install` is not usable anymore with any package. This brings me to a conclusion that I have `setuptools` 51.0 globally but when I `--upgrade` it then 51.1 is installed locally and that seems to be breaking `pip install`: ``` FROM archlinux RUN pacman -Sy --noconfirm RUN pacman -S --noconfirm python python-pip RUN pip install --user --upgrade setuptools RUN pip install --user lastversion ``` Thanks Grzegorz for the repro. With that, I think I've refined the problem a bit further. If you don't install python-pip but instead install pip from source, then also install setuptools using pip (system, then user), the problem doesn't occur: ``` FROM archlinux RUN pacman -Sy --noconfirm RUN pacman -S python wget --noconfirm RUN wget https://bootstrap.pypa.io/get-pip.py -O - | python RUN pip install setuptools RUN pip install --user --upgrade setuptools RUN pip install lastversion ``` That leads me to believe that the Arch packaging of pip (or its version) may also be implicated. Based on that, I feel like it's more Arch package than setuptools itself. I will consider reporting this issue in Arch bug tracker and I think you can close this issue here at your convenience. Thanks for helping out and mery xmas! I'm also on arch linux and have been getting this over the past couple of days. Surely it's no coincidence that mainly arch linux users are having the problem? All that I needed to do was install pip from source rather than from the arch repo: `sudo wget https://bootstrap.pypa.io/get-pip.py -O - | python` To be sure, the issue isn't strictly due to arch's `python-pip`. Changing the repro to install `setuptools<51.1` also bypasses the error, confirming the "Version 51.1" indication in the report. ``` FROM archlinux RUN pacman -Sy --noconfirm RUN pacman -S --noconfirm python python-pip RUN pip install --user --upgrade 'setuptools<51.1' RUN pip install --user lastversion ``` I looked at the [changes for 51.1](https://setuptools.readthedocs.io/en/latest/history.html#v51-1-0) and there's nothing there that strikes me as particularly implicated. Here's the diff: https://github.com/pypa/setuptools/compare/v51.0.0..v51.1.0 I wonder if maybe the issue is [this empty install_requires directive](https://github.com/pypa/setuptools/compare/v51.0.0..v51.1.0#diff-fa602a8a75dc9dcc92261bac5f533c2a85e34fcceaff63b3a3a81d9acde2fc52R29). I've used that same syntax in other projects with no declared dependencies and never had an issue with it, but it seems plausible this declaration has revealed a defect in setuptools or pip. I think I've disconfirmed that theory with this Dockerfile, which still fails: ``` FROM archlinux RUN pacman -Sy --noconfirm RUN pacman -S --noconfirm python python-pip RUN pacman -S --noconfirm git RUN git clone --branch workaround/2495-no-install-requires --depth 10 https://github.com/pypa/setuptools WORKDIR setuptools RUN python bootstrap.py RUN pip install --user . WORKDIR / CMD pip install --user lastversion ``` I also tried cleaning the indentation on the setup.cfg, but that had no effect on the failure either (6ab9f473c87058ffdc88f357d167d7f7b2750154). I tried using pdb to debug pip, but unfortunately, pip is unfriendly to debuggers: ``` [root@61533a76fa1c /]# python -m pdb -m pip install --user lastversion > /usr/lib/python3.9/site-packages/pip/__main__.py(1)<module>() -> from __future__ import absolute_import (Pdb) c Collecting lastversion Downloading lastversion-1.2.4-py3-none-any.whl (32 kB) ERROR: Exception: Traceback (most recent call last): File "/usr/lib/python3.9/site-packages/pip/_internal/cli/base_command.py", line 228, in _main status = self.run(options, args) File "/usr/lib/python3.9/site-packages/pip/_internal/cli/req_command.py", line 182, in wrapper return func(self, options, args) File "/usr/lib/python3.9/site-packages/pip/_internal/commands/install.py", line 323, in run requirement_set = resolver.resolve( File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 183, in resolve discovered_reqs.extend(self._resolve_one(requirement_set, req)) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 388, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 331, in _get_abstract_dist_for skip_reason = self._check_skip_installed(req) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 236, in _check_skip_installed req_to_install.check_if_exists(self.use_user_site) File "/usr/lib/python3.9/site-packages/pip/_internal/req/req_install.py", line 438, in check_if_exists if not self.req.specifier.contains(existing_version, prereleases=True): File "/usr/lib/python3.9/site-packages/packaging/specifiers.py", line 790, in contains item = parse(item) File "/usr/lib/python3.9/site-packages/packaging/version.py", line 57, in parse return Version(version) File "/usr/lib/python3.9/site-packages/packaging/version.py", line 296, in __init__ match = self._regex.search(version) TypeError: expected string or bytes-like object The program exited via sys.exit(). Exit status: 2 > /usr/lib/python3.9/site-packages/pip/__main__.py(1)<module>() -> from __future__ import absolute_import (Pdb) q ``` I tried installing the exact same versions of pip and setuptools to the system site-packages, and that succeeds without failure: ``` FROM archlinux RUN pacman -Sy --noconfirm RUN pacman -S --noconfirm python wget RUN wget https://bootstrap.pypa.io/get-pip.py -O - | python - pip==20.2.3 setuptools==51.0.0 RUN pip install --user --upgrade setuptools CMD pip install --user lastversion ``` So that indicates to me there are two factors at play here: - Arch packaging of `python-pip`, and - ~~Setuptools 51.1 in user-site-packages~~. Both are required to trigger the failure. I'm able to replicate the issue using a local mounted copy of setuptools for the upgrade install step ``` FROM archlinux RUN pacman -Sy --noconfirm RUN pacman -S --noconfirm wget git RUN pacman -S --noconfirm python python-pip # pip install --user . # pip install --user lastversion ``` I've tried reverting the whole setup.cfg file to the code from v51.0.0 and the problem persists, suggesting that the changes to that file aren't implicated in the issue. I will say, what's odd is my system pip location doesn't have setuptools installed (checked via `sudo pip freeze | grep setuptools`), and can't install it either (due to the issue occurring). But `pip install setuptools` will, and I'm on the latest pypi version of it too. Quite odd. Hmm. I tried `pip install --user .` against a local checkout of setuptools 51.0.0, and the error remained. I'm now beginning to think that Setuptools 51.1 isn't implicated... and the only reason I've previously been unable to replicate the issue with 51.0 was because 51.0 was the version installed by `python-pip`. Indeed, forcing a reinstall in the user directory replicates the issue without involving Setuptools 51.1: ``` FROM archlinux RUN pacman -Sy --noconfirm RUN pacman -S --noconfirm wget git RUN pacman -S --noconfirm python python-pip RUN pip install --user --force-reinstall setuptools==51 RUN pip install --user lastversion ``` > checked via `sudo pip freeze | grep setuptools` Some (all?) versions of pip will hide certain "special" packages, including setuptools. Run `pip freeze --all` to see those packages. > > checked via `sudo pip freeze | grep setuptools` > > Some (all?) versions of pip will hide certain "special" packages, including setuptools. Run `pip freeze --all` to see those packages. You're right, it shows up now. 51.1.0 on both system and user pip locations, with only user pip working. I put in some troubleshooting code in req_install.py: ```diff diff --git a/src/pip/_internal/req/req_install.py b/src/pip/_internal/req/req_install.py index f25cec96a..59d479fd6 100644 --- a/src/pip/_internal/req/req_install.py +++ b/src/pip/_internal/req/req_install.py @@ -435,6 +435,12 @@ class InstallRequirement(object): return existing_version = existing_dist.parsed_version + + try: + self.req.specifier.contains(existing_version, prereleases=True) + except TypeError: + breakpoint() + if not self.req.specifier.contains(existing_version, prereleases=True): self.satisfied_by = None if use_user_site: ``` And found these are the values present when the issue occurs: ``` pip install --user lastversion Collecting lastversion Using cached lastversion-1.2.4-py3-none-any.whl (32 kB) Collecting PyYAML Downloading PyYAML-5.3.1.tar.gz (269 kB) |████████████████████████████████| 269 kB 2.2 MB/s > /usr/lib/python3.9/site-packages/pip/_internal/req/req_install.py(444)check_if_exists() -> if not self.req.specifier.contains(existing_version, prereleases=True): (Pdb) self.req <Requirement('packaging')> (Pdb) self.req.specifier <SpecifierSet('')> (Pdb) existing_version <Version('20.8')> ``` Here's a [user reporting a very similar traceback](https://stackoverflow.com/questions/49060525/install-jupyterlab-in-pip3-throws-typeerror-expected-string-or-bytes-like-obje) in a very different environment. They never root-caused the issue. The same error doesn't occur if I pass the same inputs to the same function: ``` [root@bb62d5796f95 packaging-20.8-py3.9.egg-info]# python Python 3.9.1 (default, Dec 13 2020, 11:55:53) [GCC 10.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import packaging.requirements >>> import packaging.version >>> ver = packaging.version.Version('20.8') >>> req = packaging.requirements.Requirement('packaging') >>> req.specifier <SpecifierSet('')> >>> req.specifier.contains(ver, prereleases=True) True ``` So there's another factor present that I can't yet see. Okay, I'm pretty close to understanding the root cause. Looking at the packaging.specifiers code, I see that the `existing_version`, even though it's a "Version", is not the same "Version" as found in packaging.specifiers, so [fails this check](https://github.com/pypa/packaging/blob/d93c6eea7d2caa637176426d255895bdf7db4f64/packaging/specifiers.py#L789-L790). Back to the Pdb: ``` (Pdb) import packaging.specifiers (Pdb) isinstance(existing_version, packaging.specifiers.Version) False ``` Inspecting the class for that `existing_version`, here's what I see. ``` (Pdb) existing_version.__class__ <class 'pkg_resources.extern.packaging.version.Version'> ``` Here's loosely what's happening: - Arch de-vendors the vendored dependencies in pip and setuptools, one of which is 'packaging'. - Later, a version of setuptools is installed that includes the vendored dependencies. - Pip relies on pkg_resources, part of Setuptools, to load the installed package versions, which now defers to the user-installed setuptools with the vendored dependencies. - Packaging trips over itself when it gets a version parsed from a vendored copy of itself. I'm not sure why this problem doesn't exhibit when using pip and setuptools installed with their vendored dependencies (why do the two versions of packaging not conflict between pkg_resources._vendor and pip._vendor). Regardless, what it boils down to is that you can use one form of package management or another, but mixing arch-managed packages and pip-managed packages may encounter this issue. This issue will likely be addressed when pip moves to relying on importlib_metadata for loading package info (https://github.com/pypa/pip/issues/7413). This issue will also be alleviated if Setuptools could avoid vendoring dependencies, although that effort was tried and failed. There are probably lots of related issues. I found pypa/setuptools#1383. I'm not sure there's a lot Setuptools can do here, and it feels like there are a few options pip could take to address it, so I'm transferring this issue over to pip, although potentially it should be handled more broadly at pypa/packaging-problems. I'll let the pip maintainers decide. There are actually multiple places where pip “string-type” the version to prevent this. I’m not very motivated to work on this, however, since this is very difficult to trigger, and arguably a downstream issue that Arch packagers should be responsible for. Things might be different if this happens in other parts of pip, but the two parts that cause this issue—the legacy resolver, and `pkg_resources`—are both on their way to retirement, and a fix would become irrelevant soon. > pip is unfriendly to debugger Wait, what? This is news to me! > > pip is unfriendly to debugger > > Wait, what? This is news to me! I suspect the issue is actually PEBCAK. I wanted to use `python -m pdb -m pip` to invoke pip under a debugger, but because [pip traps exceptions](https://github.com/pypa/pip/blob/f30a02c7c26446d0e2b1b986ecbbe402795f8ccd/src/pip/_internal/cli/base_command.py#L189-L227), the debugger doesn't get a chance to intervene. If there were a better entry point that bypassed the exception trapping, or better, if pip could detect that it was running under a debugger and not trap global exceptions, that would make use of pdb much easier. No worries @jaraco! I don't know if that workflow works. I have personally used only used GUI debuggers with the debugger() callback. :) --- This is 100% because Arch is debundling pip, despite our advice to not do so in our vendoring policy. Please take this up with the Arch Linux maintainers. Also, if someone could let them know that I'm requesting them actually vendor stuff in pip, in exchange for not breaking their users in weird ways, that'd be great! :) Alternatively, users can avoid using their distro-provided pip, and use pip from get-pip.py, which won't be breakable on this manner. :) I used the get-pip via sudo, and it still fails to work via sudo pip, but regular pip now works. Please don't sudo install pip. That's a recipe for breaking your Linux distro. :( See https://stackoverflow.com/questions/15028648/is-it-acceptable-and-safe-to-run-pip-install-under-sudo for more details.
2021-01-17T22:02:14Z
[]
[]
Traceback (most recent call last): File "/usr/lib/python3.9/site-packages/pip/_internal/cli/base_command.py", line 216, in _main status = self.run(options, args) File "/usr/lib/python3.9/site-packages/pip/_internal/cli/req_command.py", line 182, in wrapper return func(self, options, args) File "/usr/lib/python3.9/site-packages/pip/_internal/commands/install.py", line 324, in run requirement_set = resolver.resolve( File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 183, in resolve discovered_reqs.extend(self._resolve_one(requirement_set, req)) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 388, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 331, in _get_abstract_dist_for skip_reason = self._check_skip_installed(req) File "/usr/lib/python3.9/site-packages/pip/_internal/resolution/legacy/resolver.py", line 236, in _check_skip_installed req_to_install.check_if_exists(self.use_user_site) File "/usr/lib/python3.9/site-packages/pip/_internal/req/req_install.py", line 437, in check_if_exists if not self.req.specifier.contains(existing_version, prereleases=True): File "/usr/lib/python3.9/site-packages/packaging/specifiers.py", line 790, in contains item = parse(item) File "/usr/lib/python3.9/site-packages/packaging/version.py", line 57, in parse return Version(version) File "/usr/lib/python3.9/site-packages/packaging/version.py", line 296, in __init__ match = self._regex.search(version) TypeError: expected string or bytes-like object
17,653
pypa/pip
pypa__pip-9537
e17ddea0e33c3dc02e823cc20bdf4990c65ce576
diff --git a/noxfile.py b/noxfile.py --- a/noxfile.py +++ b/noxfile.py @@ -174,11 +174,14 @@ def vendoring(session): def pinned_requirements(path): # type: (Path) -> Iterator[Tuple[str, str]] - for line in path.read_text().splitlines(): - one, two = line.split("==", 1) + for line in path.read_text().splitlines(keepends=False): + one, sep, two = line.partition("==") + if not sep: + continue name = one.strip() - version = two.split("#")[0].strip() - yield name, version + version = two.split("#", 1)[0].strip() + if name and version: + yield name, version vendor_txt = Path("src/pip/_vendor/vendor.txt") for name, old_version in pinned_requirements(vendor_txt):
nox -s vendoring -- --upgrade fails on Windows **Environment** * pip version: 20.3.3 * Python version: 38. * OS: Windows **Description** Using `nox -s vendoring -- --upgrade` on Windows, causes extra newlines to be added to `vendor.txt`, resulting in the process failing. **Expected behavior** The process works on Windows. **How to Reproduce** `nox -s vendoring -- --upgrade` on a Windows system. **Output** ``` >nox -s vendoring -- --upgrade nox > Running session vendoring nox > Re-using existing virtual environment at .nox\vendoring. nox > python -m pip install vendoring>=0.3.0 nox > vendoring update . appdirs Load configuration... Done! Updating requirements... Done! nox > vendoring update . CacheControl Load configuration... Done! Updating requirements... [(2, ''), (4, ''), (6, ''), (8, ''), (10, ''), (12, ''), (14, ''), (16, ''), (18, ''), (20, ''), (22, ''), (24, ''), (26, ''), (28, ''), (30, ''), (32, ''), (34, ''), (36, ''), (38, ''), (40, ''), (42, ''), (44, ''), (46, '')] nox > Session vendoring raised exception ValueError('not enough values to unpack (expected 2, got 1)') Traceback (most recent call last): File "c:\users\gustav\.local\pipx\venvs\nox\lib\site-packages\nox\sessions.py", line 549, in execute self.func(session) File "c:\users\gustav\.local\pipx\venvs\nox\lib\site-packages\nox\_decorators.py", line 53, in __call__ return self.func(*args, **kwargs) File "D:\Work\Projects\pip\noxfile.py", line 182, in vendoring for inner_name, inner_version in pinned_requirements(vendor_txt): File "D:\Work\Projects\pip\noxfile.py", line 167, in pinned_requirements one, two = line.split("==", 1) ValueError: not enough values to unpack (expected 2, got 1) nox > Session vendoring failed. ``` I suspect the issue is two-fold: the nox session doesn't handle blank lines in `vendor.txt`, but also something (possibly the vendoring tool?) is writing unnecessary blank lines?
Ping @pradyunsg What's the value of `line` here? "". Because we have extra blank lines in the file. This works on macOS, with current versions of everything, so it could be Windows only, perhaps? (`pipx run nox -s vendoring -- --upgrade`) It is Windows only, it's a line ending issue as far as I can tell.
2021-01-30T01:45:26Z
[]
[]
Traceback (most recent call last): File "c:\users\gustav\.local\pipx\venvs\nox\lib\site-packages\nox\sessions.py", line 549, in execute self.func(session) File "c:\users\gustav\.local\pipx\venvs\nox\lib\site-packages\nox\_decorators.py", line 53, in __call__ return self.func(*args, **kwargs) File "D:\Work\Projects\pip\noxfile.py", line 182, in vendoring for inner_name, inner_version in pinned_requirements(vendor_txt): File "D:\Work\Projects\pip\noxfile.py", line 167, in pinned_requirements one, two = line.split("==", 1) ValueError: not enough values to unpack (expected 2, got 1)
17,657
pypa/pip
pypa__pip-9684
15459969b30510ec5275bb865806596bd3feef8a
diff --git a/src/pip/_internal/locations/_distutils.py b/src/pip/_internal/locations/_distutils.py --- a/src/pip/_internal/locations/_distutils.py +++ b/src/pip/_internal/locations/_distutils.py @@ -3,6 +3,7 @@ # The following comment should be removed at some point in the future. # mypy: strict-optional=False +import logging import os import sys from distutils.cmd import Command as DistutilsCommand @@ -17,6 +18,8 @@ from .base import get_major_minor_version +logger = logging.getLogger(__name__) + def _distutils_scheme( dist_name: str, @@ -36,7 +39,15 @@ def _distutils_scheme( dist_args["script_args"] = ["--no-user-cfg"] d = Distribution(dist_args) - d.parse_config_files() + try: + d.parse_config_files() + except UnicodeDecodeError: + # Typeshed does not include find_config_files() for some reason. + paths = d.find_config_files() # type: ignore + logger.warning( + "Ignore distutils configs in %s due to encoding errors.", + ", ".join(os.path.basename(p) for p in paths), + ) obj: Optional[DistutilsCommand] = None obj = d.get_command_obj("install", create=True) assert obj is not None
PIP doesn't read setup.cfg in UTF-8, which causes UnicodeDecodeError <!-- If you're reporting an issue for `--use-feature=2020-resolver`, use the "Dependency resolver failures / errors" template instead. --> **Environment** * pip version: 20.2.3 * Python version: 3.8.5 * OS: Win7x64 **Description** When installing anything within a path that has a setup.cfg, pip will read it but fails at decoding if the file contains non-ASCII characters. The cfg file is proper UTF-8 but PIP doesn't open it as so. It tries to use "GBK" (my locale) and fails. Related, but not the same issue: #8717 (this is caused by `pyvenv.cfg`) **Expected behavior** It should read setup.cfg in UTF-8. **How to Reproduce** 1. open a path. 2. Create a `setup.cfg` file with ``` [metadata] name = test version = 0.0.1 packages = test description = '計算ツール' ``` 3. Run `pip install requests` **Output** ``` D:\test>pip install requests ERROR: Exception: Traceback (most recent call last): File "c:\program files\python3\lib\site-packages\pip\_internal\cli\base_command.py", line 228, in _main status = self.run(options, args) File "c:\program files\python3\lib\site-packages\pip\_internal\cli\req_command.py", line 182, in wrapper return func(self, options, args) File "c:\program files\python3\lib\site-packages\pip\_internal\commands\install.py", line 245, in run options.use_user_site = decide_user_install( File "c:\program files\python3\lib\site-packages\pip\_internal\commands\install.py", line 664, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "c:\program files\python3\lib\site-packages\pip\_internal\commands\install.py", line 609, in site_packages_writab le get_lib_location_guesses(root=root, isolated=isolated)) File "c:\program files\python3\lib\site-packages\pip\_internal\commands\install.py", line 600, in get_lib_location_gue sses scheme = distutils_scheme('', user=user, home=home, root=root, File "c:\program files\python3\lib\site-packages\pip\_internal\locations.py", line 109, in distutils_scheme d.parse_config_files() File "c:\program files\python3\lib\distutils\dist.py", line 406, in parse_config_files parser.read(filename) File "c:\program files\python3\lib\configparser.py", line 697, in read self._read(fp, filename) File "c:\program files\python3\lib\configparser.py", line 1017, in _read for lineno, line in enumerate(fp, start=1): UnicodeDecodeError: 'gbk' codec can't decode byte 0xab in position 88: illegal multibyte sequence ```
distutils is a built-in module, you’ll need to file the issue against CPython instead. https://bugs.python.org/ Thanks for the quick reply. Interestingly, `setuptools` itself doesn't fail with such cfg file. Are they doing something different? I was also wondering why we read setup.cfg to begin with for a global installation. OK, it looks to me setuptools work arounds this issue on their own (https://github.com/pypa/setuptools/pull/1180), is there any chance we do the same? I feel like `distutils` may have to be that way for backward compatibility reasons. I knew this probably is too much to ask, so feel free to do what you think is the best. Man, they basically re-implemented the whole thing. I’m not sure pip should be responsible to maintaining this implementation. Maybe we should just catch the parsing error and carry on pretending the file does not exist instead. pip does not actually need any of the data you mentioned above; it just reads [distutils configuration](https://docs.python.org/2.5/inst/config-syntax.html). The usage is honestly quite niche, and I doubt many would even notice the difference. Oh yeah, totally agreed with you. If we don't need anything ciritial from cfg file (or, at least, *in case* it isn't, like global installation shown here), it's reasonable to just ignore the error. Today this issue bit me too in jaraco/configparser#58. Thinking about this more, this needs to be reimplemented eventually when pip migrates off distutils anyway, so we may as well do it right now. @jaraco Would it be a good idea if we extract setuptools’s config-parsing implementation into a standalone library that pip can vendor? In the case of distutils_scheme, there's currently an [effort underway to deprecate distutils](https://discuss.python.org/t/pep-632-deprecate-distutils-module/5134) in which the distutils-schemes are being ported to the `sysconfig` module. It's hard for me to say, but I'm a little reluctant to say that we should break out just the "parse config files" behavior into a separate library. On the other hand, that would eliminate one aspect of the dependency on distutils and limit the divergence from setuptools, so perhaps that makes sense. Is this still a thing in pip 20.3? Just tested, still broken here. ``` (v) D:\temp>python -m pip install pip -U Collecting pip Using cached pip-20.3-py2.py3-none-any.whl (1.5 MB) Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 20.1.1 Uninstalling pip-20.1.1: Successfully uninstalled pip-20.1.1 Successfully installed pip-20.3 (v) D:\temp>pip install requests Collecting requests Using cached requests-2.25.0-py2.py3-none-any.whl (61 kB) Collecting certifi>=2017.4.17 Using cached certifi-2020.11.8-py2.py3-none-any.whl (155 kB) Collecting chardet<4,>=3.0.2 Using cached chardet-3.0.4-py2.py3-none-any.whl (133 kB) Collecting idna<3,>=2.5 Using cached idna-2.10-py2.py3-none-any.whl (58 kB) Collecting urllib3<1.27,>=1.21.1 Using cached urllib3-1.26.2-py2.py3-none-any.whl (136 kB) Installing collected packages: urllib3, idna, chardet, certifi, requests ERROR: Exception: Traceback (most recent call last): File "d:\temp\v\lib\site-packages\pip\_internal\cli\base_command.py", line 210, in _main status = self.run(options, args) File "d:\temp\v\lib\site-packages\pip\_internal\cli\req_command.py", line 180, in wrapper return func(self, options, args) File "d:\temp\v\lib\site-packages\pip\_internal\commands\install.py", line 392, in run installed = install_given_reqs( File "d:\temp\v\lib\site-packages\pip\_internal\req\__init__.py", line 82, in install_given_reqs requirement.install( File "d:\temp\v\lib\site-packages\pip\_internal\req\req_install.py", line 781, in install scheme = get_scheme( File "d:\temp\v\lib\site-packages\pip\_internal\locations.py", line 184, in get_scheme scheme = distutils_scheme( File "d:\temp\v\lib\site-packages\pip\_internal\locations.py", line 108, in distutils_scheme d.parse_config_files() File "C:\Program Files\Python3\lib\distutils\dist.py", line 406, in parse_config_files parser.read(filename) File "C:\Program Files\Python3\lib\configparser.py", line 697, in read self._read(fp, filename) File "C:\Program Files\Python3\lib\configparser.py", line 1017, in _read for lineno, line in enumerate(fp, start=1): UnicodeDecodeError: 'gbk' codec can't decode byte 0xab in position 93: illegal multibyte sequence (v) D:\temp> ``` (Having the same `setup.cfg` above in cwd) Since distutils is deprecated and [slated for removal in 3.12](https://www.python.org/dev/peps/pep-0632/), maybe this is a good idea now? Yeah. The code path will eventually be removed altogether and replaced by an equivalent based on `sysconfig`. The migration has started in #9626, but the road ahead is still long. Also the new implementation does not currently contain the cfg parsing logic at all, and if no-one complains maybe we can just kill that feature entirely. What was it used for? It can be used to control certain distutils (and by extension setuptools) behaviours, like what directory to store intermediate objects during build, compiler options, etc. Very low-level, implementation-dependant stuffs, and some even in direct conflict with other pip options, so hopefully nobody is using them, but I’ve seen pip users use worse “features”. Why not a quick and dirty fix to suppress the error when it occurs and while at it, deprecate the code path, so if it is parsed _and_ it contains settings that affect pip, raise warnings that it's going away, thereby detecting users who might be relying on it? I'm also okay with just removing the behavior and seeing who cries as long as there's a rapid response to bring the behavior back or an escape hatch to re-enable the behavior. The logic is buried deep in distutils and triggered when pip calls distutils to know where to install stuff into, distutils does not offer a way to disable the behaviour. So pip can’t just suppress the error since it needs those values to function, and the only way out of this (from what I can tell) is to remove reliance on those distutils values, which is what #9626 is going for. I was under the impression that it was this line that was raising: https://github.com/pypa/pip/blob/e7d6e54dff0ef93197624c51cbde264dc390c511/src/pip/_internal/locations/_distutils.py#L35 Would it not be possible to wrap it in a try-except? We can, but the location behaviour would change in subtle ways when that fails 😟 But now that I think of it, maybe that’d still be a good enough stopgap before we purge distutils? Nothing would change if the parsing succeeds (which is most of the time), and the behaviour will “mostly work” when it fails, which might be good enough. What does "mostly work" mean? If I have, say: ``` [install] install_scripts = foo ``` in my `setup.cfg` and the parsing fails then the scripts would not be where I expect. (Although this is already rather fragile because pip does not respect distutils configuration when uninstalling packages.) That would not fail though. The parsing would only fail if the file contains content not decodable with the platform encoding. distutils also reads multiple config locations, including system-wide `distutils.cfg`, and for values like `home`, `prefix`, etc. which are honoured on uninstallation IIRC. Those are likely the more “popular” existing usages (although likely still not very wide-spread at this point, at least I hope not). > That would not fail though. The parsing would only fail if the file contains content not decodable with the platform encoding. Yeah, I understand that.
2021-03-04T13:07:07Z
[]
[]
Traceback (most recent call last): File "c:\program files\python3\lib\site-packages\pip\_internal\cli\base_command.py", line 228, in _main status = self.run(options, args) File "c:\program files\python3\lib\site-packages\pip\_internal\cli\req_command.py", line 182, in wrapper return func(self, options, args) File "c:\program files\python3\lib\site-packages\pip\_internal\commands\install.py", line 245, in run options.use_user_site = decide_user_install( File "c:\program files\python3\lib\site-packages\pip\_internal\commands\install.py", line 664, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "c:\program files\python3\lib\site-packages\pip\_internal\commands\install.py", line 609, in site_packages_writab le
17,666
pypa/pip
pypa__pip-9993
e6414d6db6db37951988f6f2b11ec530ed0b191d
diff --git a/src/pip/_internal/resolution/resolvelib/factory.py b/src/pip/_internal/resolution/resolvelib/factory.py --- a/src/pip/_internal/resolution/resolvelib/factory.py +++ b/src/pip/_internal/resolution/resolvelib/factory.py @@ -240,18 +240,29 @@ def _iter_found_candidates( hashes &= ireq.hashes(trust_internet=False) extras |= frozenset(ireq.extras) - # Get the installed version, if it matches, unless the user - # specified `--force-reinstall`, when we want the version from - # the index instead. - installed_candidate = None - if not self._force_reinstall and name in self._installed_dists: - installed_dist = self._installed_dists[name] - if specifier.contains(installed_dist.version, prereleases=True): - installed_candidate = self._make_candidate_from_dist( - dist=installed_dist, - extras=extras, - template=template, - ) + def _get_installed_candidate() -> Optional[Candidate]: + """Get the candidate for the currently-installed version.""" + # If --force-reinstall is set, we want the version from the index + # instead, so we "pretend" there is nothing installed. + if self._force_reinstall: + return None + try: + installed_dist = self._installed_dists[name] + except KeyError: + return None + # Don't use the installed distribution if its version does not fit + # the current dependency graph. + if not specifier.contains(installed_dist.version, prereleases=True): + return None + candidate = self._make_candidate_from_dist( + dist=installed_dist, + extras=extras, + template=template, + ) + # The candidate is a known incompatiblity. Don't use it. + if id(candidate) in incompatible_ids: + return None + return candidate def iter_index_candidate_infos(): # type: () -> Iterator[IndexCandidateInfo] @@ -283,7 +294,7 @@ def iter_index_candidate_infos(): return FoundCandidates( iter_index_candidate_infos, - installed_candidate, + _get_installed_candidate(), prefers_installed, incompatible_ids, )
pip 21.1 fails with ResolutionTooDeep while 21.0.1 exits with clear error ### Description pip 21.0.1 has no error and highlights the dependency error right away while pip 2.1 runs for minutes then throws a _ResolutionTooDeep_ exception. ### Expected behavior pip version 21.0.1 produces the expected output which includes this diagnostic: ``` The conflict is caused by: The user requested hyperlink==19.0.0 autobahn 20.12.3 depends on hyperlink>=20.0.1 ``` ### pip version 21.1 ### Python version 3.6.13 ### OS Ubuntu 16.04.7 LTS ### How to Reproduce 1. Create a python3.6 virtualenv 2. activate 3. Ensure pip v21.1 is installed in the virtualenv 4. run `pip -r r.txt` where r.txt has this content: ``` attrs==19.3.0 autobahn==20.6.2 hyperlink==19.0.0 cffi==1.14.0 cryptography>=3.2 idna==2.10 pycparser==2.20 txaio==20.4.1 ``` 5. Replace `autobahn==20.6.2` with `autobahn==20.12.3` in r.txt 6. run `pip -r r.txt` ### Output ```sh-session Lots of spew, then: Requirement already satisfied: txaio==20.4.1 in ./venv/lib/python3.6/site-packages (from -rr test.txt (line 8)) (20.4.1) INFO: pip is looking at multiple versions of attrs to determine which version is compatible with other requirements. This could take a while. Then pip seems to hang. If you wait long enough: 5 minutes? it prints: ERROR: Exception: Traceback (most recent call last): File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 180, in _main status = self.run(options, args) File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 204, in wrapper return func(self, options, args) File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 319, in run reqs, check_supported_wheels=not options.target_dir File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 128, in resolve requirements, max_rounds=try_to_avoid_resolution_too_deep File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_vendor/resolvelib/resolvers.py", line 473, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_vendor/resolvelib/resolvers.py", line 384, in resolve raise ResolutionTooDeep(max_rounds) pip._vendor.resolvelib.resolvers.ResolutionTooDeep: 2000000 ``` ### Code of Conduct - [X] I agree to follow the [PSF Code of Conduct](https://www.python.org/psf/conduct/).
FYI the versions are 21.0.1 and 21.1, not 2.0 and 2.1. You’re one digit off. Ahh. What's a digit here or there :) I updated the original comment. I'm also facing this error. @junpuf Please describe what you were doing when you encountered the issue. Hi @uranusjr Sorry for the delayed response. I have seen this error from one of my conda environment build process using `environment.yml`, and pip dependencies were used and listed below: ``` "boto3", "s3fs", "multi-model-server==1.1.2", "keras-mxnet==2.2.4.2", "opencv-python==4.5.1.48" ``` Below are the error message. ``` Collecting aiobotocore>=1.0.1 Downloading aiobotocore-1.3.0.tar.gz (48 kB) Downloading aiobotocore-1.2.2.tar.gz (48 kB) Downloading aiobotocore-1.2.1.tar.gz (48 kB) Downloading aiobotocore-1.2.0.tar.gz (47 kB) Downloading aiobotocore-1.1.2-py3-none-any.whl (45 kB) Downloading aiobotocore-1.1.1-py3-none-any.whl (45 kB) Downloading aiobotocore-1.1.0-py3-none-any.whl (43 kB) Downloading aiobotocore-1.0.7-py3-none-any.whl (42 kB) Downloading aiobotocore-1.0.6-py3-none-any.whl (42 kB) Downloading aiobotocore-1.0.5-py3-none-any.whl (42 kB) Downloading aiobotocore-1.0.4-py3-none-any.whl (41 kB) Downloading aiobotocore-1.0.3-py3-none-any.whl (40 kB) Downloading aiobotocore-1.0.2-py3-none-any.whl (40 kB) Downloading aiobotocore-1.0.1-py3-none-any.whl (40 kB) INFO: pip is looking at multiple versions of fsspec to determine which version is compatible with other requirements. This could take a while. Pip subprocess error: ERROR: Exception: ... ... pip._vendor.resolvelib.resolvers.ResolutionTooDeep: 2000000 ··failed CondaEnvException: Pip failed ``` Thanks for the test cases! I have identified the issue and will post a patch shortly.
2021-05-18T14:59:10Z
[]
[]
Traceback (most recent call last): File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_internal/cli/base_command.py", line 180, in _main status = self.run(options, args) File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_internal/cli/req_command.py", line 204, in wrapper return func(self, options, args) File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_internal/commands/install.py", line 319, in run reqs, check_supported_wheels=not options.target_dir File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 128, in resolve requirements, max_rounds=try_to_avoid_resolution_too_deep File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_vendor/resolvelib/resolvers.py", line 473, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "/home/sigma/dev/contour/daqAdaptor/venv/lib/python3.6/site-packages/pip/_vendor/resolvelib/resolvers.py", line 384, in resolve raise ResolutionTooDeep(max_rounds) pip._vendor.resolvelib.resolvers.ResolutionTooDeep: 2000000
17,680
ray-project/ray
ray-project__ray-10078
739933e5b84291dea54c29fc6acc982a3d42a52f
diff --git a/python/ray/autoscaler/command_runner.py b/python/ray/autoscaler/command_runner.py --- a/python/ray/autoscaler/command_runner.py +++ b/python/ray/autoscaler/command_runner.py @@ -556,6 +556,7 @@ def run( ssh_options_override_ssh_key=ssh_options_override_ssh_key) def run_rsync_up(self, source, target): + # TODO(ilr) Expose this to before NodeUpdater::sync_file_mounts protected_path = target if target.find("/root") == 0: target = target.replace("/root", "/tmp/root") diff --git a/python/ray/autoscaler/updater.py b/python/ray/autoscaler/updater.py --- a/python/ray/autoscaler/updater.py +++ b/python/ray/autoscaler/updater.py @@ -145,8 +145,9 @@ def do_sync(remote_path, local_path, allow_non_existing_paths=False): with LogTimer(self.log_prefix + "Synced {} to {}".format(local_path, remote_path)): - self.cmd_runner.run("mkdir -p {}".format( - os.path.dirname(remote_path))) + self.cmd_runner.run( + "mkdir -p {}".format(os.path.dirname(remote_path)), + run_env="host") sync_cmd(local_path, remote_path) if remote_path not in nolog_paths: @@ -188,7 +189,7 @@ def wait_ready(self, deadline): "{}Waiting for remote shell...", self.log_prefix) - self.cmd_runner.run("uptime") + self.cmd_runner.run("uptime", run_env="host") cli_logger.old_debug(logger, "Uptime succeeded.") cli_logger.success("Success.") return True
Docker + AWS fails with no such container error Latest dev version of ray ``` (vanilla_ray_venv) richard@richard-desktop:~/improbable/vanillas/ray/python/ray/autoscaler/aws$ ray up aws_gpu_dummy.yaml 2020-08-12 20:12:39,383 INFO config.py:268 -- _configure_iam_role: Role not specified for head node, using arn:aws:iam::179622923911:instance-profile/ray-autoscaler-v1 2020-08-12 20:12:39,612 INFO config.py:346 -- _configure_key_pair: KeyName not specified for nodes, using ray-autoscaler_us-east-1 2020-08-12 20:12:39,745 INFO config.py:407 -- _configure_subnet: SubnetIds not specified for head node, using [('subnet-f737f791', 'us-east-1a')] 2020-08-12 20:12:39,746 INFO config.py:417 -- _configure_subnet: SubnetId not specified for workers, using [('subnet-f737f791', 'us-east-1a')] 2020-08-12 20:12:40,358 INFO config.py:590 -- _create_security_group: Created new security group ray-autoscaler-richard_cluster_gpu_dummy (sg-0061ca6aff182c1bf) 2020-08-12 20:12:40,739 INFO config.py:444 -- _configure_security_group: SecurityGroupIds not specified for head node, using ray-autoscaler-richard_cluster_gpu_dummy (sg-0061ca6aff182c1bf) 2020-08-12 20:12:40,739 INFO config.py:454 -- _configure_security_group: SecurityGroupIds not specified for workers, using ray-autoscaler-richard_cluster_gpu_dummy (sg-0061ca6aff182c1bf) This will create a new cluster [y/N]: y 2020-08-12 20:12:42,619 INFO commands.py:531 -- get_or_create_head_node: Launching new head node... 2020-08-12 20:12:42,620 INFO node_provider.py:326 -- NodeProvider: calling create_instances with subnet-f737f791 (count=1). 2020-08-12 20:12:44,032 INFO node_provider.py:354 -- NodeProvider: Created instance [id=i-0729c7a86355d5ff8, name=pending, info=pending] 2020-08-12 20:12:44,223 INFO commands.py:570 -- get_or_create_head_node: Updating files on head node... 2020-08-12 20:12:44,320 INFO command_runner.py:331 -- NodeUpdater: i-0729c7a86355d5ff8: Waiting for IP... 2020-08-12 20:12:54,409 INFO command_runner.py:331 -- NodeUpdater: i-0729c7a86355d5ff8: Waiting for IP... 2020-08-12 20:12:54,534 INFO log_timer.py:27 -- NodeUpdater: i-0729c7a86355d5ff8: Got IP [LogTimer=10310ms] 2020-08-12 20:12:54,534 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && command -v docker' Warning: Permanently added '3.226.253.119' (ECDSA) to the list of known hosts. /usr/bin/docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:04,587 INFO updater.py:71 -- NodeUpdater: i-0729c7a86355d5ff8: Updating to 6b5fc8ee8c5dcdf3cfabe0bf90ba4e844f65a7c9 2020-08-12 20:14:04,587 INFO updater.py:180 -- NodeUpdater: i-0729c7a86355d5ff8: Waiting for remote shell... 2020-08-12 20:14:04,587 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' 2020-08-12 20:14:04,950 INFO log_timer.py:27 -- AWSNodeProvider: Set tag ray-node-status=waiting-for-ssh on ['i-0729c7a86355d5ff8'] [LogTimer=361ms] Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:21,222 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:26,417 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:31,610 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:36,798 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:41,986 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:47,170 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:52,358 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:14:57,554 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:15:02,750 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:15:07,938 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:15:13,126 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:15:18,307 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:15:23,494 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. Shared connection to 3.226.253.119 closed. 2020-08-12 20:19:01,502 INFO command_runner.py:468 -- NodeUpdater: i-0729c7a86355d5ff8: Running ssh -tt -i /home/richard/.ssh/ray-autoscaler_us-east-1.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ControlMaster=auto -o ControlPath=/tmp/ray_ssh_6ae199a93c/cfde1c79f1/%C -o ControlPersist=10s -o ConnectTimeout=120s ubuntu@3.226.253.119 bash --login -c -i 'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && docker exec -it pytorch_docker /bin/bash -c '"'"'bash --login -c -i '"'"'"'"'"'"'"'"'true && source ~/.bashrc && export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && uptime'"'"'"'"'"'"'"'"''"'"' ' Error: No such container: pytorch_docker Shared connection to 3.226.253.119 closed. 2020-08-12 20:19:06,689 INFO log_timer.py:27 -- NodeUpdater: i-0729c7a86355d5ff8: Got remote shell [LogTimer=302102ms] 2020-08-12 20:19:06,690 INFO log_timer.py:27 -- NodeUpdater: i-0729c7a86355d5ff8: Applied config 6b5fc8ee8c5dcdf3cfabe0bf90ba4e844f65a7c9 [LogTimer=302103ms] 2020-08-12 20:19:06,690 ERROR updater.py:88 -- NodeUpdater: i-0729c7a86355d5ff8: Error executing: Unable to connect to node Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/home/richard/improbable/vanillas/ray/python/ray/autoscaler/updater.py", line 76, in run self.do_update() File "/home/richard/improbable/vanillas/ray/python/ray/autoscaler/updater.py", line 232, in do_update self.wait_ready(deadline) File "/home/richard/improbable/vanillas/ray/python/ray/autoscaler/updater.py", line 224, in wait_ready assert False, "Unable to connect to node" AssertionError: Unable to connect to node 2020-08-12 20:19:06,962 ERROR commands.py:650 -- get_or_create_head_node: Updating 3.226.253.119 failed 2020-08-12 20:19:07,002 INFO log_timer.py:27 -- AWSNodeProvider: Set tag ray-node-status=update-failed on ['i-0729c7a86355d5ff8'] [LogTimer=312ms] ``` YAML file for repo attached. ``` # An unique identifier for the head node and workers of this cluster. cluster_name: richard_cluster_gpu_dummy # The minimum number of workers nodes to launch in addition to the head # node. This number should be >= 0. min_workers: 1 # The maximum number of workers nodes to launch in addition to the head # node. This takes precedence over min_workers. max_workers: 5 # The initial number of worker nodes to launch in addition to the head # node. When the cluster is first brought up (or when it is refreshed with a # subsequent `ray up`) this number of nodes will be started. initial_workers: 1 # Whether or not to autoscale aggressively. If this is enabled, if at any point # we would start more workers, we start at least enough to bring us to # initial_workers. autoscaling_mode: default # This executes all commands on all nodes in the docker efcontainer, # and opens all the necessary ports to support the Ray cluster. # Empty string means disabled. docker: image: "pytorch/pytorch:latest" # e.g., tensorflow/tensorflow:1.5.0-py3 container_name: "pytorch_docker" # e.g. ray_docker # If true, pulls latest version of image. Otherwise, `docker run` will only pull the image # if no cached version is present. pull_before_run: True run_options: [] # - $([ -d /proc/driver ] && echo -n --runtime-nvidia) # Use the nvidia runtime only if nvidia gpu's are installed worker_run_options: - --runtime=nvidia # Extra options to pass into "docker run" # Example of running a GPU head with CPU workers # head_image: "tensorflow/tensorflow:1.13.1-py3" # head_run_options: # - --runtime=nvidia # worker_image: "ubuntu:18.04" # worker_run_options: [] # The autoscaler will scale up the cluster to this target fraction of resource # usage. For example, if a cluster of 10 nodes is 100% busy and # target_utilization is 0.8, it would resize the cluster to 13. This fraction # can be decreased to increase the aggressiveness of upscaling. # This value must be less than 1.0 for scaling to happen. target_utilization_fraction: 0.8 # If a node is idle for this many minutes, it will be removed. idle_timeout_minutes: 5 # Cloud-provider specific configuration. provider: type: aws region: us-east-1 # Availability zone(s), comma-separated, that nodes may be launched in. # Nodes are currently spread between zones by a round-robin approach, # however this implementation detail should not be relied upon. availability_zone: us-east-1a, us-east-1b cache_stopped_nodes: False # How Ray will authenticate with newly launched nodes. auth: ssh_user: ubuntu # By default Ray creates a new private keypair, but you can also use your own. # If you do so, make sure to also set "KeyName" in the head and worker node # configurations below. # ssh_private_key: /path/to/your/key.pem # Provider-specific config for the head node, e.g. instance type. By default # Ray will auto-configure unspecified fields such as SubnetId and KeyName. # For more documentation on available fields, see: # http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances head_node: InstanceType: c4.2xlarge ImageId: ami-043f9aeaf108ebc37 # Deep Learning AMI (Ubuntu) Version 24.3 # You can provision additional disk space with a conf as follows BlockDeviceMappings: - DeviceName: /dev/sda1 Ebs: VolumeSize: 100 # Additional options in the boto docs. # Provider-specific config for worker nodes, e.g. instance type. By default # Ray will auto-configure unspecified fields such as SubnetId and KeyName. # For more documentation on available fields, see: # http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances worker_nodes: InstanceType: p3.2xlarge ImageId: ami-043f9aeaf108ebc37 # Deep Learning AMI (Ubuntu) Version 24.3 # Run workers on spot by default. Comment this out to use on-demand. InstanceMarketOptions: MarketType: spot # Additional options can be found in the boto docs, e.g. # SpotOptions: # MaxPrice: MAX_HOURLY_PRICE # Additional options in the boto docs. # Files or directories to copy to the head and worker nodes. The format is a # dictionary from REMOTE_PATH: LOCAL_PATH, e.g. file_mounts: { } # List of commands that will be run before `setup_commands`. If docker is # enabled, these commands will run outside the container and before docker # is setup. initialization_commands: [] # List of shell commands to run to set up nodes. setup_commands: # Note: if you're developing Ray, you probably want to create an AMI that # has your Ray repo pre-cloned. Then, you can replace the pip installs # below with a git checkout <your_sha> (and possibly a recompile). - pip install -U https://s3-us-west-2.amazonaws.com/ray-wheels/latest/ray-0.9.0.dev0-cp37-cp37m-manylinux1_x86_64.whl # - pip install -U https://s3-us-west-2.amazonaws.com/ray-wheels/latest/ray-0.9.0.dev0-cp37-cp37m-manylinux1_x86_64.whl # Consider uncommenting these if you also want to run apt-get commands during setup # - sudo pkill -9 apt-get || true # - sudo pkill -9 dpkg || true # - sudo dpkg --configure -a # Custom commands that will be run on the head node after common setup. head_setup_commands: - pip install boto3 # 1.4.8 adds InstanceMarketOptions # Custom commands that will be run on worker nodes after common setup. worker_setup_commands: - pip install boto3 # 1.4.8 adds InstanceMarketOptions # Command to start ray on the head node. You don't need to change this. head_start_ray_commands: - ray stop - ulimit -n 65536; ray start --num-cpus=0 --head --port=6379 --object-manager-port=8076 --autoscaling-config=~/ray_bootstrap_config.yaml # Command to start ray on worker nodes. You don't need to change this. worker_start_ray_commands: - ray stop - ulimit -n 65536; ray start --address=$RAY_HEAD_IP:6379 --object-manager-port=8076 ```
2020-08-13T01:01:46Z
[]
[]
Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/home/richard/improbable/vanillas/ray/python/ray/autoscaler/updater.py", line 76, in run self.do_update() File "/home/richard/improbable/vanillas/ray/python/ray/autoscaler/updater.py", line 232, in do_update self.wait_ready(deadline) File "/home/richard/improbable/vanillas/ray/python/ray/autoscaler/updater.py", line 224, in wait_ready assert False, "Unable to connect to node" AssertionError: Unable to connect to node
17,687
ray-project/ray
ray-project__ray-10122
c7adb464e49db7309cf4084d698dae7968b8e2e3
diff --git a/rllib/offline/off_policy_estimator.py b/rllib/offline/off_policy_estimator.py --- a/rllib/offline/off_policy_estimator.py +++ b/rllib/offline/off_policy_estimator.py @@ -1,10 +1,13 @@ from collections import namedtuple import logging +import numpy as np + from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch from ray.rllib.policy import Policy from ray.rllib.utils.annotations import DeveloperAPI from ray.rllib.offline.io_context import IOContext +from ray.rllib.utils.numpy import convert_to_numpy from ray.rllib.utils.typing import TensorType, SampleBatchType from typing import List @@ -53,7 +56,7 @@ def estimate(self, batch: SampleBatchType): raise NotImplementedError @DeveloperAPI - def action_prob(self, batch: SampleBatchType) -> TensorType: + def action_prob(self, batch: SampleBatchType) -> np.ndarray: """Returns the probs for the batch actions for the current policy.""" num_state_inputs = 0 @@ -61,13 +64,13 @@ def action_prob(self, batch: SampleBatchType) -> TensorType: if k.startswith("state_in_"): num_state_inputs += 1 state_keys = ["state_in_{}".format(i) for i in range(num_state_inputs)] - log_likelihoods = self.policy.compute_log_likelihoods( + log_likelihoods: TensorType = self.policy.compute_log_likelihoods( actions=batch[SampleBatch.ACTIONS], obs_batch=batch[SampleBatch.CUR_OBS], state_batches=[batch[k] for k in state_keys], prev_action_batch=batch.data.get(SampleBatch.PREV_ACTIONS), prev_reward_batch=batch.data.get(SampleBatch.PREV_REWARDS)) - return log_likelihoods + return convert_to_numpy(log_likelihoods) @DeveloperAPI def process(self, batch: SampleBatchType):
[rllib] Off Policy Estimation breaks with GPU on PyTorch (MARWIL) (Offline API) ### What is the problem? When I use MARWIL with PyTorch and num_gpus: 1, I get an error when computing metrics. This happens because in off policy estimation it uses the torch tensors on gpu instead of numpy arrays. Particularly, I use "input_evaluation": ["is", "wis"] and the error goes away when "input_evaluation": ["simulation"] ``` Traceback (most recent call last): File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\tune\trial_runner.py", line 497, in _process_trial result = self.trial_executor.fetch_result(trial) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\tune\ray_trial_executor.py", line 434, in fetch_result result = ray.get(trial_future[0], DEFAULT_GET_TIMEOUT) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\worker.py", line 1553, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError(AttributeError): ray::MARWIL.train() (pid=9136, ip=10.0.0.18) File "python\ray\_raylet.pyx", line 474, in ray._raylet.execute_task File "python\ray\_raylet.pyx", line 427, in ray._raylet.execute_task.function_executor File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\function_manager.py", line 567, in actor_method_executor raise e File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\function_manager.py", line 559, in actor_method_executor method_returns = method(actor, *args, **kwargs) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\rllib\agents\trainer.py", line 522, in train raise e File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\rllib\agents\trainer.py", line 508, in train result = Trainable.train(self) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\tune\trainable.py", line 337, in train result = self.step() File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\rllib\agents\trainer_template.py", line 110, in step res = next(self.train_exec_impl) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\util\iter.py", line 758, in __next__ return next(self.built_iterator) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\util\iter.py", line 793, in apply_foreach result = fn(item) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\rllib\execution\metric_ops.py", line 87, in __call__ res = summarize_episodes(episodes, orig_episodes) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\rllib\evaluation\metrics.py", line 173, in summarize_episodes metrics[k] = np.mean(v_list) File "<__array_function__ internals>", line 6, in mean File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\numpy\core\fromnumeric.py", line 3335, in mean out=out, **kwargs) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\numpy\core\_methods.py", line 161, in _mean ret = ret.dtype.type(ret / rcount) AttributeError: 'torch.dtype' object has no attribute 'type' ``` ### Reproduction (REQUIRED) Please provide a script that can be run to reproduce the issue. The script should have **no external library dependencies** (i.e., use fake or mock data / environments): If we cannot run your script, we cannot fix your issue. - [ ] I have verified my script runs in a clean environment and reproduces the issue. - [ ] I have verified the issue also occurs with the [latest wheels](https://docs.ray.io/en/latest/installation.html).
Hmm I think we are missing a call to `.cpu().numpy()` somewhere and are trying to calculate a np.mean() over torch tensors representing a single element. Do you think you could look into this issue?
2020-08-14T23:29:31Z
[]
[]
Traceback (most recent call last): File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\tune\trial_runner.py", line 497, in _process_trial result = self.trial_executor.fetch_result(trial) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\tune\ray_trial_executor.py", line 434, in fetch_result result = ray.get(trial_future[0], DEFAULT_GET_TIMEOUT) File "C:\Users\Julius\Anaconda3\envs\ray\lib\site-packages\ray\worker.py", line 1553, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError(AttributeError): ray::MARWIL.train() (pid=9136, ip=10.0.0.18)
17,689
ray-project/ray
ray-project__ray-10531
2a7f56e42926d3b481eb27edf7bab0dbe5ab73b9
diff --git a/python/ray/tune/schedulers/hb_bohb.py b/python/ray/tune/schedulers/hb_bohb.py --- a/python/ray/tune/schedulers/hb_bohb.py +++ b/python/ray/tune/schedulers/hb_bohb.py @@ -93,7 +93,7 @@ def _unpause_trial(self, trial_runner, trial): trial_runner.trial_executor.unpause_trial(trial) trial_runner._search_alg.searcher.on_unpause(trial.trial_id) - def choose_trial_to_run(self, trial_runner): + def choose_trial_to_run(self, trial_runner, allow_recurse=True): """Fair scheduling within iteration by completion percentage. List of trials not used since all trials are tracked as state @@ -117,8 +117,17 @@ def choose_trial_to_run(self, trial_runner): for bracket in hyperband: if bracket and any(trial.status == Trial.PAUSED for trial in bracket.current_trials()): - # This will change the trial state and let the - # trial runner retry. + # This will change the trial state self._process_bracket(trial_runner, bracket) + + # If there are pending trials now, suggest one. + # This is because there might be both PENDING and + # PAUSED trials now, and PAUSED trials will raise + # an error before the trial runner tries again. + if allow_recurse and any( + trial.status == Trial.PENDING + for trial in bracket.current_trials()): + return self.choose_trial_to_run( + trial_runner, allow_recurse=False) # MAIN CHANGE HERE! return None diff --git a/python/ray/tune/schedulers/hyperband.py b/python/ray/tune/schedulers/hyperband.py --- a/python/ray/tune/schedulers/hyperband.py +++ b/python/ray/tune/schedulers/hyperband.py @@ -282,7 +282,8 @@ def debug_string(self): for i, band in enumerate(self._hyperbands): out += "\nRound #{}:".format(i) for bracket in band: - out += "\n {}".format(bracket) + if bracket: + out += "\n {}".format(bracket) return out def state(self):
[tune] BOHB with DQN and MountainCar-v0 fails <!--Please include [tune], [rllib], [autoscaler] etc. in the issue title if relevant--> ### What is the problem? I am using BOHB to optimize the hyperparameters for the DQN algorithm in order to solve the MountainCar-v0 problem. I alway run into the following issue (even if I use different values for num_samples): ```python == Status == Memory usage on this node: 7.0/15.6 GiB Using HyperBand: num_stopped=832 total_brackets=3 Round #0: None Bracket(Max Size (n)=2, Milestone (r)=1458, completed=100.0%): {RUNNING: 1, TERMINATED: 833} Bracket(Max Size (n)=324, Milestone (r)=8, completed=47.3%): {PAUSED: 166} Resources requested: 4/32 CPUs, 0/0 GPUs, 0.0/8.69 GiB heap, 0.0/2.98 GiB objects Result logdir: /home/dl-user/ray_results/MCv0_DQN_BOHB Number of trials: 1000 (166 PAUSED, 1 RUNNING, 833 TERMINATED) +-----------------------------+------------+----------------------+-------------------+-------------+--------------------+--------+------------------+--------+----------+ | Trial name | status | loc | batch_mode | lr | train_batch_size | iter | total time (s) | ts | reward | |-----------------------------+------------+----------------------+-------------------+-------------+--------------------+--------+------------------+--------+----------| | DQN_MountainCar-v0_0428be42 | PAUSED | | truncate_episodes | 1.99095e-05 | 408 | 2 | 25.6885 | 4032 | -200 | | DQN_MountainCar-v0_0428be45 | PAUSED | | truncate_episodes | 0.000382289 | 211 | 2 | 24.7536 | 5040 | -200 | | DQN_MountainCar-v0_0428be48 | PAUSED | | truncate_episodes | 0.000324929 | 233 | 2 | 25.5532 | 5040 | -200 | | DQN_MountainCar-v0_0747e5f2 | PAUSED | | truncate_episodes | 0.000114766 | 38 | 2 | 23.8492 | 7056 | -200 | | DQN_MountainCar-v0_0747e5f5 | PAUSED | | truncate_episodes | 9.1226e-05 | 200 | 2 | 24.2349 | 5040 | -200 | | DQN_MountainCar-v0_08218bf0 | PAUSED | | truncate_episodes | 0.000284028 | 69 | 2 | 25.3671 | 7056 | -200 | | DQN_MountainCar-v0_093c0b8c | PAUSED | | truncate_episodes | 0.00237606 | 114 | 2 | 23.3935 | 6048 | -200 | | DQN_MountainCar-v0_0a55eae6 | PAUSED | | truncate_episodes | 0.000417829 | 111 | 2 | 23.4849 | 6048 | -200 | | DQN_MountainCar-v0_0b307d56 | PAUSED | | truncate_episodes | 0.000196047 | 59 | 2 | 23.1338 | 7056 | -200 | | DQN_MountainCar-v0_0eedea91 | PAUSED | | truncate_episodes | 6.58278e-05 | 59 | 2 | 24.0254 | 7056 | -200 | | DQN_MountainCar-v0_1fcd888b | RUNNING | 172.16.160.219:47910 | truncate_episodes | 0.000237864 | 751 | 88 | 1638.34 | 199584 | -122.05 | | DQN_MountainCar-v0_0023f4f6 | TERMINATED | | truncate_episodes | 0.000255833 | 158 | 1 | 5.56779 | 1008 | -200 | | DQN_MountainCar-v0_0023f4f9 | TERMINATED | | complete_episodes | 0.000262904 | 156 | 1 | 5.43817 | 1200 | -200 | | DQN_MountainCar-v0_0023f4fc | TERMINATED | | complete_episodes | 0.0002605 | 260 | 1 | 5.33452 | 1200 | -200 | | DQN_MountainCar-v0_0108428e | TERMINATED | | truncate_episodes | 3.89327e-05 | 732 | 4 | 36.2218 | 5040 | -200 | | DQN_MountainCar-v0_01084291 | TERMINATED | | truncate_episodes | 2.39745e-05 | 714 | 4 | 36.2585 | 5040 | -200 | | DQN_MountainCar-v0_01084294 | TERMINATED | | truncate_episodes | 4.9252e-05 | 808 | 4 | 38.4182 | 5040 | -200 | | DQN_MountainCar-v0_01084297 | TERMINATED | | truncate_episodes | 7.42384e-05 | 804 | 4 | 38.0425 | 5040 | -200 | | DQN_MountainCar-v0_014223c0 | TERMINATED | | truncate_episodes | 0.0520328 | 71 | 1 | 6.21906 | 1008 | -200 | | DQN_MountainCar-v0_01939ac4 | TERMINATED | | complete_episodes | 8.34678e-05 | 124 | 1 | 5.37302 | 1200 | -200 | | DQN_MountainCar-v0_01a4cc45 | TERMINATED | | complete_episodes | 0.00973094 | 373 | 3 | 27.2147 | 24000 | -200 | +-----------------------------+------------+----------------------+-------------------+-------------+--------------------+--------+------------------+--------+----------+ ... 980 more trials not shown (156 PAUSED, 823 TERMINATED) Traceback (most recent call last): File "/home/dl-user/python-code/modularized_version_ray/ray_BOHB.py", line 123, in <module> verbose=1, File "/home/dl-user/.local/lib/python3.7/site-packages/ray/tune/tune.py", line 327, in run runner.step() File "/home/dl-user/.local/lib/python3.7/site-packages/ray/tune/trial_runner.py", line 342, in step self.trial_executor.on_no_available_trials(self) File "/home/dl-user/.local/lib/python3.7/site-packages/ray/tune/trial_executor.py", line 177, in on_no_available_trials raise TuneError("There are paused trials, but no more pending " ray.tune.error.TuneError: There are paused trials, but no more pending trials with sufficient resources. Process finished with exit code 1 ``` By the way, why is the first bracket ``none``? And also it seems that the whole process was pretty slow. Is there any systematic way to find out the bottlenecks? You guys are doing a great job with this framework! Thanks in advance for your help! *Ray version and other system information (Python version, TensorFlow version, OS):* OS: Ubuntu 16.04 Python Version: 3.7.8 Ray Version: 0.8.6 ### Reproduction (REQUIRED) ```python import ray from ray import tune from ray.tune.suggest.bohb import TuneBOHB from ray.tune.schedulers.hb_bohb import HyperBandForBOHB import ConfigSpace as CS ray.init() config_space = CS.ConfigurationSpace() config_space.add_hyperparameter(CS.UniformFloatHyperparameter("lr", lower=0.00001, upper=0.1, log=True)) config_space.add_hyperparameter(CS.UniformIntegerHyperparameter("train_batch_size", lower=32, upper=1024, log=False)) config_space.add_hyperparameter(CS.CategoricalHyperparameter("batch_mode", choices=['truncate_episodes', 'complete_episodes'])) bohb_search = TuneBOHB( space=config_space, bohb_config=None, max_concurrent=32, metric='episode_reward_mean', mode='max' ) bohb_hyperband = HyperBandForBOHB( time_attr='episodes_total', metric='episode_reward_mean', mode='max', max_t=2000, reduction_factor=3, ) config = { "env": "MountainCar-v0", "min_iter_time_s": 15, "num_gpus": 0, "num_workers": 1, "double_q": True, "n_step": 3, "target_network_update_freq": 1000, "buffer_size": 20000, # "prioritzed_replay": True, "learning_starts": 1000, "log_level": "ERROR" } analysis = tune.run( run_or_experiment="DQN", name='MCv0_DQN_BOHB', config=config, num_samples=1000, checkpoint_at_end=True, search_alg=bohb_search, scheduler=bohb_hyperband, verbose=1, ) ``` Please provide a script that can be run to reproduce the issue. The script should have **no external library dependencies** (i.e., use fake or mock data / environments): If we cannot run your script, we cannot fix your issue. - [x] I have verified my script runs in a clean environment and reproduces the issue. - [ ] I have verified the issue also occurs with the [latest wheels](https://docs.ray.io/en/latest/installation.html).
Hey - I have a very similar issue with BOHB, with very similar code to above. It seems to work when you use "training_iteration" but not when you use episodes or timesteps, with batch size as a hyperparameter. It seems to break when the number of update steps is not uniform across agents. Not sure if this helps someone resolve the issue. It would be great if it can be resolved!
2020-09-03T13:23:21Z
[]
[]
Traceback (most recent call last): File "/home/dl-user/python-code/modularized_version_ray/ray_BOHB.py", line 123, in <module> verbose=1, File "/home/dl-user/.local/lib/python3.7/site-packages/ray/tune/tune.py", line 327, in run runner.step() File "/home/dl-user/.local/lib/python3.7/site-packages/ray/tune/trial_runner.py", line 342, in step self.trial_executor.on_no_available_trials(self) File "/home/dl-user/.local/lib/python3.7/site-packages/ray/tune/trial_executor.py", line 177, in on_no_available_trials raise TuneError("There are paused trials, but no more pending " ray.tune.error.TuneError: There are paused trials, but no more pending trials with sufficient resources.
17,702
ray-project/ray
ray-project__ray-10672
d7c7aba99cc2e6383af605aaa4671f4266fad979
diff --git a/python/ray/scripts/scripts.py b/python/ray/scripts/scripts.py --- a/python/ray/scripts/scripts.py +++ b/python/ray/scripts/scripts.py @@ -622,7 +622,7 @@ def start(node_ip_address, redis_address, address, redis_port, port, " ray stop".format( redis_address, " --redis-password='" + redis_password + "'" if redis_password else "", - ", redis_password='" + redis_password + "'" + ", _redis_password='" + redis_password + "'" if redis_password else "")) else: # Start Ray on a non-head node. @@ -1472,7 +1472,7 @@ def memory(address, redis_password): if not address: address = services.find_redis_address_or_die() logger.info(f"Connecting to Ray instance at {address}.") - ray.init(address=address, redis_password=redis_password) + ray.init(address=address, _redis_password=redis_password) print(ray.internal.internal_api.memory_summary())
A lot of Ray commands fail in nightly build <!--Please include [tune], [rllib], [autoscaler] etc. in the issue title if relevant--> ### What is the problem? This is because they keep passing the deleted `redis_password` keyword. For example, ``` $ ray memory 2020-09-09 05:24:50,248 INFO scripts.py:1474 -- Connecting to Ray instance at 172.31.56.46:6379. Traceback (most recent call last): File "/home/ubuntu/anaconda3/bin/ray", line 8, in <module> sys.exit(main()) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/scripts/scripts.py", line 1602, in main return cli() File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/scripts/scripts.py", line 1475, in memory ray.init(address=address, redis_password=redis_password) TypeError: init() got an unexpected keyword argument 'redis_password' ``` Also I feel confused about many prompts and docs still mentioning `redis_password` while it no longer exists in `ray.init` ### Reproduction (REQUIRED) Please provide a script that can be run to reproduce the issue. The script should have **no external library dependencies** (i.e., use fake or mock data / environments): If we cannot run your script, we cannot fix your issue. - [ ] I have verified my script runs in a clean environment and reproduces the issue. - [ ] I have verified the issue also occurs with the [latest wheels](https://docs.ray.io/en/latest/installation.html).
2020-09-09T06:13:47Z
[]
[]
Traceback (most recent call last): File "/home/ubuntu/anaconda3/bin/ray", line 8, in <module> sys.exit(main()) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/scripts/scripts.py", line 1602, in main return cli() File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 782, in main rv = self.invoke(ctx) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 1259, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 1066, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/click/core.py", line 610, in invoke return callback(*args, **kwargs) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/ray/scripts/scripts.py", line 1475, in memory ray.init(address=address, redis_password=redis_password) TypeError: init() got an unexpected keyword argument 'redis_password'
17,710
ray-project/ray
ray-project__ray-10680
799318d7d785881b7dc89aad817284683a4ea4f5
diff --git a/python/ray/tune/integration/wandb.py b/python/ray/tune/integration/wandb.py --- a/python/ray/tune/integration/wandb.py +++ b/python/ray/tune/integration/wandb.py @@ -9,6 +9,8 @@ from ray.tune.logger import Logger from ray.tune.utils import flatten_dict +import yaml + try: import wandb except ImportError: @@ -29,6 +31,12 @@ def _clean_log(obj): # Else try: pickle.dumps(obj) + yaml.dump( + obj, + Dumper=yaml.SafeDumper, + default_flow_style=False, + allow_unicode=True, + encoding="utf-8") return obj except Exception: # give up, similar to _SafeFallBackEncoder
[rllib] Weights & Biases logger cannot handle objects in configuration <!--Please include [tune], [rllib], [autoscaler] etc. in the issue title if relevant--> ### What is the problem? The Weights & Biases logger cannot handle object references in RLlib configurations, for example in the callback API. ``` Process _WandbLoggingProcess-1: Traceback (most recent call last): File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap self.run() File "[...]/ray/tune/integration/wandb.py", line 127, in run wandb.init(*self.args, **self.kwargs) File "[...]/wandb/__init__.py", line 1303, in init as_defaults=not allow_val_change) File "[...]/wandb/wandb_config.py", line 333, in _update self.persist() File "[...]/wandb/wandb_config.py", line 238, in persist conf_file.write(str(self)) File "[...]/wandb/wandb_config.py", line 374, in __str__ allow_unicode=True, encoding='utf-8') File "[...]/yaml/__init__.py", line 290, in dump return dump_all([data], stream, Dumper=Dumper, **kwds) File "[...]/yaml/__init__.py", line 278, in dump_all dumper.represent(data) File "[...]/yaml/representer.py", line 27, in represent node = self.represent_data(data) File "[...]/yaml/representer.py", line 48, in represent_data node = self.yaml_representers[data_types[0]](self, data) File "[...]/yaml/representer.py", line 207, in represent_dict return self.represent_mapping('tag:yaml.org,2002:map', data) File "[...]/yaml/representer.py", line 118, in represent_mapping node_value = self.represent_data(item_value) File "[...]/yaml/representer.py", line 48, in represent_data node = self.yaml_representers[data_types[0]](self, data) File "[...]/yaml/representer.py", line 207, in represent_dict return self.represent_mapping('tag:yaml.org,2002:map', data) File "[...]/yaml/representer.py", line 118, in represent_mapping node_value = self.represent_data(item_value) File "[...]/yaml/representer.py", line 58, in represent_data node = self.yaml_representers[None](self, data) File "[...]/yaml/representer.py", line 231, in represent_undefined raise RepresenterError("cannot represent an object", data) yaml.representer.RepresenterError: ('cannot represent an object', <class '__main__.MyCallbacks'>) ``` *Ray version and other system information (Python version, TensorFlow version, OS):* - Ray 0.8.7 - Ubuntu 18.04 - Python 3.7 ### Reproduction (REQUIRED) Please provide a script that can be run to reproduce the issue. The script should have **no external library dependencies** (i.e., use fake or mock data / environments): ``` from ray import tune from ray.rllib.agents.ppo import PPOTrainer from ray.rllib.agents.callbacks import DefaultCallbacks from ray.tune.integration.wandb import WandbLogger class MyCallbacks(DefaultCallbacks): def on_episode_end(self, worker, base_env, policies, episode, **kwargs): print("Episode ended") tune.run( PPOTrainer, checkpoint_freq=1, config={ "framework": "torch", "num_workers": 8, "num_gpus": 1, "env": "CartPole-v0", "callbacks": MyCallbacks, "logger_config": { "wandb": { "project": "test", "api_key_file": "./wandb_api_key_file", } } }, stop={ "training_iteration":10 }, loggers=[WandbLogger] ) ``` If we cannot run your script, we cannot fix your issue. - [X] I have verified my script runs in a clean environment and reproduces the issue. - [X] I have verified the issue also occurs with the [latest wheels](https://docs.ray.io/en/latest/installation.html).
I noticed that the callback is already [explicitly filtered out in the result handling](https://github.com/ray-project/ray/blob/0aec4cbccb5862a7808f98b90696236da9e2a03e/python/ray/tune/integration/wandb.py#L159), but of course that doesn't help during initialization. Is there any reason why objects shouldn't be generally filtered out? Probably only numbers and strings make sense to log anyway? cc @krfricke Thanks. For the moment I submitted a [tiny PR](https://github.com/ray-project/ray/pull/10441) to fix the callback API specifically. I agree it makes sense to filter out invalid values, I'll get back to this soon. @krfricke I am having a similar problem trying to use APPO (PPO works fine). See https://pastebin.com/SdpNp0Pq Hey @janblumenkamp and @rhamnett this should be fixed via #10654. If this issue prevails, feel free to re-open! @krfricke @richardliaw Afraid that I am still seeing the same error when running an APPO tune job Hi @rhamnett, did you install the latest nightly ray release? Do you have a script to reproduce the error? @krfricke yes I am familiar with re-installing the nightly and can confirm that I have done that correctly. My script is lengthy and contains private intellectual property, so I am wondering if you can just simply adapt a PPO test you might have to APPO (should be trivial) and then let me know if you can re-produce? If after trying that, you can't reproduce, I will seek to dedicate some time to give you an example script.
2020-09-09T17:18:24Z
[]
[]
Traceback (most recent call last): File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap self.run() File "[...]/ray/tune/integration/wandb.py", line 127, in run wandb.init(*self.args, **self.kwargs) File "[...]/wandb/__init__.py", line 1303, in init as_defaults=not allow_val_change) File "[...]/wandb/wandb_config.py", line 333, in _update self.persist() File "[...]/wandb/wandb_config.py", line 238, in persist conf_file.write(str(self)) File "[...]/wandb/wandb_config.py", line 374, in __str__ allow_unicode=True, encoding='utf-8') File "[...]/yaml/__init__.py", line 290, in dump return dump_all([data], stream, Dumper=Dumper, **kwds) File "[...]/yaml/__init__.py", line 278, in dump_all dumper.represent(data) File "[...]/yaml/representer.py", line 27, in represent node = self.represent_data(data) File "[...]/yaml/representer.py", line 48, in represent_data node = self.yaml_representers[data_types[0]](self, data) File "[...]/yaml/representer.py", line 207, in represent_dict return self.represent_mapping('tag:yaml.org,2002:map', data) File "[...]/yaml/representer.py", line 118, in represent_mapping node_value = self.represent_data(item_value) File "[...]/yaml/representer.py", line 48, in represent_data node = self.yaml_representers[data_types[0]](self, data) File "[...]/yaml/representer.py", line 207, in represent_dict return self.represent_mapping('tag:yaml.org,2002:map', data) File "[...]/yaml/representer.py", line 118, in represent_mapping node_value = self.represent_data(item_value) File "[...]/yaml/representer.py", line 58, in represent_data node = self.yaml_representers[None](self, data) File "[...]/yaml/representer.py", line 231, in represent_undefined raise RepresenterError("cannot represent an object", data) yaml.representer.RepresenterError: ('cannot represent an object', <class '__main__.MyCallbacks'>)
17,711
ray-project/ray
ray-project__ray-1457
21a916009eb4705690c26037bf593ee0b6135cca
diff --git a/examples/parameter_server/async_parameter_server.py b/examples/parameter_server/async_parameter_server.py --- a/examples/parameter_server/async_parameter_server.py +++ b/examples/parameter_server/async_parameter_server.py @@ -3,11 +3,9 @@ from __future__ import print_function import argparse -from tensorflow.examples.tutorials.mnist import input_data import time import ray - import model parser = argparse.ArgumentParser(description="Run the asynchronous parameter " @@ -35,9 +33,9 @@ def pull(self, keys): @ray.remote -def worker_task(ps, batch_size=50): +def worker_task(ps, worker_index, batch_size=50): # Download MNIST. - mnist = input_data.read_data_sets("MNIST_data", one_hot=True) + mnist = model.download_mnist_retry(seed=worker_index) # Initialize the model. net = model.SimpleCNN() @@ -65,10 +63,10 @@ def worker_task(ps, batch_size=50): ps = ParameterServer.remote(all_keys, all_values) # Start some training tasks. - worker_tasks = [worker_task.remote(ps) for _ in range(args.num_workers)] + worker_tasks = [worker_task.remote(ps, i) for i in range(args.num_workers)] # Download MNIST. - mnist = input_data.read_data_sets("MNIST_data", one_hot=True) + mnist = model.download_mnist_retry() i = 0 while True: diff --git a/examples/parameter_server/model.py b/examples/parameter_server/model.py --- a/examples/parameter_server/model.py +++ b/examples/parameter_server/model.py @@ -8,6 +8,18 @@ import ray import tensorflow as tf +from tensorflow.examples.tutorials.mnist import input_data +import time + + +def download_mnist_retry(seed=0, max_num_retries=20): + for _ in range(max_num_retries): + try: + return input_data.read_data_sets("MNIST_data", one_hot=True, + seed=seed) + except tf.errors.AlreadyExistsError: + time.sleep(1) + raise Exception("Failed to download MNIST.") class SimpleCNN(object): diff --git a/examples/parameter_server/sync_parameter_server.py b/examples/parameter_server/sync_parameter_server.py --- a/examples/parameter_server/sync_parameter_server.py +++ b/examples/parameter_server/sync_parameter_server.py @@ -3,9 +3,7 @@ from __future__ import print_function import argparse - import numpy as np -from tensorflow.examples.tutorials.mnist import input_data import ray import model @@ -36,8 +34,7 @@ class Worker(object): def __init__(self, worker_index, batch_size=50): self.worker_index = worker_index self.batch_size = batch_size - self.mnist = input_data.read_data_sets("MNIST_data", one_hot=True, - seed=worker_index) + self.mnist = model.download_mnist_retry(seed=worker_index) self.net = model.SimpleCNN() def compute_gradients(self, weights): @@ -60,7 +57,7 @@ def compute_gradients(self, weights): for worker_index in range(args.num_workers)] # Download MNIST. - mnist = input_data.read_data_sets("MNIST_data", one_hot=True) + mnist = model.download_mnist_retry() i = 0 current_weights = ps.get_weights.remote()
Error in parameter server examples when multiple workers try to download MNIST at the same time. To reproduce the example, run the following (making sure that `ray/examples/parameter_server/` does not have a copy of the MNIST data set) ``` cd ray/examples/parameter_server/ python async_parameter_server.py ``` Some tasks threw the following error ``` Remote function __main__.worker_task failed with: Traceback (most recent call last): File "async_parameter_server.py", line 40, in worker_task mnist = input_data.read_data_sets("MNIST_data", one_hot=True) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 245, in read_data_sets source_url + TRAIN_LABELS) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 209, in maybe_download gfile.Copy(temp_file_name, filepath) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/tensorflow/python/lib/io/file_io.py", line 385, in copy compat.as_bytes(oldpath), compat.as_bytes(newpath), overwrite, status) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.AlreadyExistsError: file already exists ``` The same error can probably occur with the sync parameter server as well.
2018-01-24T00:20:43Z
[]
[]
Traceback (most recent call last): File "async_parameter_server.py", line 40, in worker_task mnist = input_data.read_data_sets("MNIST_data", one_hot=True) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py", line 245, in read_data_sets source_url + TRAIN_LABELS) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 209, in maybe_download gfile.Copy(temp_file_name, filepath) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/tensorflow/python/lib/io/file_io.py", line 385, in copy compat.as_bytes(oldpath), compat.as_bytes(newpath), overwrite, status) File "/home/ubuntu/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.AlreadyExistsError: file already exists
17,748
ray-project/ray
ray-project__ray-1668
adffc7bfea10ae70e6e5ef39847c2ecfb3b6e77a
diff --git a/doc/source/conf.py b/doc/source/conf.py --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -37,7 +37,8 @@ "ray.plasma", "ray.core.generated.TaskInfo", "ray.core.generated.TaskReply", - "ray.core.generated.ResultTableReply"] + "ray.core.generated.ResultTableReply", + "ray.core.generated.TaskExecutionDependencies"] for mod_name in MOCK_MODULES: sys.modules[mod_name] = mock.Mock() diff --git a/python/ray/actor.py b/python/ray/actor.py --- a/python/ray/actor.py +++ b/python/ray/actor.py @@ -12,8 +12,7 @@ import ray.local_scheduler import ray.signature as signature import ray.worker -from ray.utils import (binary_to_hex, FunctionProperties, random_string, - release_gpus_in_use, select_local_scheduler, is_cython, +from ray.utils import (FunctionProperties, random_string, is_cython, push_error_to_driver) @@ -47,6 +46,18 @@ def compute_actor_handle_id(actor_handle_id, num_forks): return ray.local_scheduler.ObjectID(handle_id) +def compute_actor_creation_function_id(class_id): + """Compute the function ID for an actor creation task. + + Args: + class_id: The ID of the actor class. + + Returns: + The function ID of the actor creation event. + """ + return ray.local_scheduler.ObjectID(class_id) + + def compute_actor_method_function_id(class_name, attr): """Get the function ID corresponding to an actor method. @@ -222,12 +233,17 @@ def actor_method_executor(dummy_return_id, actor, *args): return actor_method_executor -def fetch_and_register_actor(actor_class_key, worker): +def fetch_and_register_actor(actor_class_key, resources, worker): """Import an actor. This will be called by the worker's import thread when the worker receives the actor_class export, assuming that the worker is an actor for that class. + + Args: + actor_class_key: The key in Redis to use to fetch the actor. + resources: The resources required for this actor's lifetime. + worker: The worker to use. """ actor_id_str = worker.actor_id (driver_id, class_id, class_name, @@ -258,7 +274,7 @@ def temporary_actor_method(*xs): raise Exception("The actor with name {} failed to be imported, and so " "cannot execute this method".format(actor_name)) # Register the actor method signatures. - register_actor_signatures(worker, driver_id, class_name, + register_actor_signatures(worker, driver_id, class_id, class_name, actor_method_names, actor_method_num_return_vals) # Register the actor method executors. for actor_method_name in actor_method_names: @@ -306,26 +322,25 @@ def temporary_actor_method(*xs): # because we currently do need the actor worker to submit new tasks # for the actor. - # Store some extra information that will be used when the actor exits - # to release GPU resources. - worker.driver_id = binary_to_hex(driver_id) - local_scheduler_id = worker.redis_client.hget( - b"Actor:" + actor_id_str, "local_scheduler_id") - worker.local_scheduler_id = binary_to_hex(local_scheduler_id) - -def register_actor_signatures(worker, driver_id, class_name, +def register_actor_signatures(worker, driver_id, class_id, class_name, actor_method_names, - actor_method_num_return_vals): + actor_method_num_return_vals, + actor_creation_resources=None, + actor_method_cpus=None): """Register an actor's method signatures in the worker. Args: worker: The worker to register the signatures on. driver_id: The ID of the driver that this actor is associated with. - actor_id: The ID of the actor. + class_id: The ID of the actor class. + class_name: The name of the actor class. actor_method_names: The names of the methods to register. actor_method_num_return_vals: A list of the number of return values for each of the actor's methods. + actor_creation_resources: The resources required by the actor creation + task. + actor_method_cpus: The number of CPUs required by each actor method. """ assert len(actor_method_names) == len(actor_method_num_return_vals) for actor_method_name, num_return_vals in zip( @@ -337,8 +352,19 @@ def register_actor_signatures(worker, driver_id, class_name, actor_method_name).id() worker.function_properties[driver_id][function_id] = ( # The extra return value is an actor dummy object. + # In the cases where actor_method_cpus is None, that value should + # never be used. FunctionProperties(num_return_vals=num_return_vals + 1, - resources={"CPU": 1}, + resources={"CPU": actor_method_cpus}, + max_calls=0)) + + if actor_creation_resources is not None: + # Also register the actor creation task. + function_id = compute_actor_creation_function_id(class_id) + worker.function_properties[driver_id][function_id.id()] = ( + # The extra return value is an actor dummy object. + FunctionProperties(num_return_vals=0 + 1, + resources=actor_creation_resources, max_calls=0)) @@ -393,7 +419,8 @@ def export_actor_class(class_id, Class, actor_method_names, def export_actor(actor_id, class_id, class_name, actor_method_names, - actor_method_num_return_vals, resources, worker): + actor_method_num_return_vals, actor_creation_resources, + actor_method_cpus, worker): """Export an actor to redis. Args: @@ -403,8 +430,9 @@ def export_actor(actor_id, class_id, class_name, actor_method_names, actor_method_names (list): A list of the names of this actor's methods. actor_method_num_return_vals: A list of the number of return values for each of the actor's methods. - resources: A dictionary mapping resource name to the quantity of that - resource required by the actor. + actor_creation_resources: A dictionary mapping resource name to the + quantity of that resource required by the actor. + actor_method_cpus: The number of CPUs required by actor methods. """ ray.worker.check_main_thread() if worker.mode is None: @@ -412,33 +440,15 @@ def export_actor(actor_id, class_id, class_name, actor_method_names, "started. You can start Ray with 'ray.init()'.") driver_id = worker.task_driver_id.id() - register_actor_signatures(worker, driver_id, class_name, - actor_method_names, actor_method_num_return_vals) - - # Select a local scheduler for the actor. - key = b"Actor:" + actor_id.id() - local_scheduler_id = select_local_scheduler( - worker.task_driver_id.id(), ray.global_state.local_schedulers(), - resources.get("GPU", 0), worker.redis_client) - assert local_scheduler_id is not None - - # We must put the actor information in Redis before publishing the actor - # notification so that when the newly created actor attempts to fetch the - # information from Redis, it is already there. - driver_id = worker.task_driver_id.id() - worker.redis_client.hmset(key, {"class_id": class_id, - "driver_id": driver_id, - "local_scheduler_id": local_scheduler_id, - "num_gpus": resources.get("GPU", 0), - "removed": False}) + register_actor_signatures( + worker, driver_id, class_id, class_name, actor_method_names, + actor_method_num_return_vals, + actor_creation_resources=actor_creation_resources, + actor_method_cpus=actor_method_cpus) - # TODO(rkn): There is actually no guarantee that the local scheduler that - # we are publishing to has already subscribed to the actor_notifications - # channel. Therefore, this message may be missed and the workload will - # hang. This is a bug. - ray.utils.publish_actor_creation(actor_id.id(), driver_id, - local_scheduler_id, False, - worker.redis_client) + args = [class_id] + function_id = compute_actor_creation_function_id(class_id) + return worker.submit_task(function_id, args, actor_creation_id=actor_id)[0] def method(*args, **kwargs): @@ -479,10 +489,16 @@ class ActorHandleWrapper(object): This is essentially just a dictionary, but it is used so that the recipient can tell that an argument is an ActorHandle. """ - def __init__(self, actor_id, actor_handle_id, actor_cursor, actor_counter, - actor_method_names, actor_method_num_return_vals, - method_signatures, checkpoint_interval, class_name): + def __init__(self, actor_id, class_id, actor_handle_id, actor_cursor, + actor_counter, actor_method_names, + actor_method_num_return_vals, method_signatures, + checkpoint_interval, class_name, + actor_creation_dummy_object_id, + actor_creation_resources, actor_method_cpus): + # TODO(rkn): Some of these fields are probably not necessary. We should + # strip out the unnecessary fields to keep actor handles lightweight. self.actor_id = actor_id + self.class_id = class_id self.actor_handle_id = actor_handle_id self.actor_cursor = actor_cursor self.actor_counter = actor_counter @@ -493,6 +509,9 @@ def __init__(self, actor_id, actor_handle_id, actor_cursor, actor_counter, self.method_signatures = method_signatures self.checkpoint_interval = checkpoint_interval self.class_name = class_name + self.actor_creation_dummy_object_id = actor_creation_dummy_object_id + self.actor_creation_resources = actor_creation_resources + self.actor_method_cpus = actor_method_cpus def wrap_actor_handle(actor_handle): @@ -506,6 +525,7 @@ def wrap_actor_handle(actor_handle): """ wrapper = ActorHandleWrapper( actor_handle._ray_actor_id, + actor_handle._ray_class_id, compute_actor_handle_id(actor_handle._ray_actor_handle_id, actor_handle._ray_actor_forks), actor_handle._ray_actor_cursor, @@ -514,7 +534,10 @@ def wrap_actor_handle(actor_handle): actor_handle._ray_actor_method_num_return_vals, actor_handle._ray_method_signatures, actor_handle._ray_checkpoint_interval, - actor_handle._ray_class_name) + actor_handle._ray_class_name, + actor_handle._ray_actor_creation_dummy_object_id, + actor_handle._ray_actor_creation_resources, + actor_handle._ray_actor_method_cpus) actor_handle._ray_actor_forks += 1 return wrapper @@ -530,21 +553,27 @@ def unwrap_actor_handle(worker, wrapper): The unwrapped ActorHandle instance. """ driver_id = worker.task_driver_id.id() - register_actor_signatures(worker, driver_id, wrapper.class_name, - wrapper.actor_method_names, - wrapper.actor_method_num_return_vals) + register_actor_signatures(worker, driver_id, wrapper.class_id, + wrapper.class_name, wrapper.actor_method_names, + wrapper.actor_method_num_return_vals, + wrapper.actor_creation_resources, + wrapper.actor_method_cpus) actor_handle_class = make_actor_handle_class(wrapper.class_name) actor_object = actor_handle_class.__new__(actor_handle_class) actor_object._manual_init( wrapper.actor_id, + wrapper.class_id, wrapper.actor_handle_id, wrapper.actor_cursor, wrapper.actor_counter, wrapper.actor_method_names, wrapper.actor_method_num_return_vals, wrapper.method_signatures, - wrapper.checkpoint_interval) + wrapper.checkpoint_interval, + wrapper.actor_creation_dummy_object_id, + wrapper.actor_creation_resources, + wrapper.actor_method_cpus) return actor_object @@ -569,11 +598,13 @@ def remote(cls, *args, **kwargs): raise NotImplementedError("The classmethod remote() can only be " "called on the original Class.") - def _manual_init(self, actor_id, actor_handle_id, actor_cursor, - actor_counter, actor_method_names, + def _manual_init(self, actor_id, class_id, actor_handle_id, + actor_cursor, actor_counter, actor_method_names, actor_method_num_return_vals, method_signatures, - checkpoint_interval): + checkpoint_interval, actor_creation_dummy_object_id, + actor_creation_resources, actor_method_cpus): self._ray_actor_id = actor_id + self._ray_class_id = class_id self._ray_actor_handle_id = actor_handle_id self._ray_actor_cursor = actor_cursor self._ray_actor_counter = actor_counter @@ -584,6 +615,10 @@ def _manual_init(self, actor_id, actor_handle_id, actor_cursor, self._ray_checkpoint_interval = checkpoint_interval self._ray_class_name = class_name self._ray_actor_forks = 0 + self._ray_actor_creation_dummy_object_id = ( + actor_creation_dummy_object_id) + self._ray_actor_creation_resources = actor_creation_resources + self._ray_actor_method_cpus = actor_method_cpus def _actor_method_call(self, method_name, args=None, kwargs=None, dependency=None): @@ -640,6 +675,8 @@ def _actor_method_call(self, method_name, args=None, kwargs=None, actor_handle_id=self._ray_actor_handle_id, actor_counter=self._ray_actor_counter, is_actor_checkpoint_method=is_actor_checkpoint_method, + actor_creation_dummy_object_id=( + self._ray_actor_creation_dummy_object_id), execution_dependencies=execution_dependencies) # Update the actor counter and cursor to reflect the most recent # invocation. @@ -691,13 +728,16 @@ def __del__(self): # with Class.remote(). if (ray.worker.global_worker.connected and self._ray_actor_handle_id.id() == ray.worker.NIL_ACTOR_ID): + # TODO(rkn): Should we be passing in the actor cursor as a + # dependency here? self._actor_method_call("__ray_terminate__", args=[self._ray_actor_id.id()]) return ActorHandle -def actor_handle_from_class(Class, class_id, resources, checkpoint_interval): +def actor_handle_from_class(Class, class_id, actor_creation_resources, + checkpoint_interval, actor_method_cpus): class_name = Class.__name__.encode("ascii") actor_handle_class = make_actor_handle_class(class_name) exported = [] @@ -764,22 +804,28 @@ def remote(cls, *args, **kwargs): checkpoint_interval, ray.worker.global_worker) exported.append(0) - export_actor(actor_id, class_id, class_name, - actor_method_names, actor_method_num_return_vals, - resources, ray.worker.global_worker) + actor_cursor = export_actor(actor_id, class_id, class_name, + actor_method_names, + actor_method_num_return_vals, + actor_creation_resources, + actor_method_cpus, + ray.worker.global_worker) # Instantiate the actor handle. actor_object = cls.__new__(cls) - actor_object._manual_init(actor_id, actor_handle_id, actor_cursor, - actor_counter, actor_method_names, + actor_object._manual_init(actor_id, class_id, actor_handle_id, + actor_cursor, actor_counter, + actor_method_names, actor_method_num_return_vals, - method_signatures, - checkpoint_interval) + method_signatures, checkpoint_interval, + actor_cursor, actor_creation_resources, + actor_method_cpus) # Call __init__ as a remote function. if "__init__" in actor_object._ray_actor_method_names: actor_object._actor_method_call("__init__", args=args, - kwargs=kwargs) + kwargs=kwargs, + dependency=actor_cursor) else: print("WARNING: this object has no __init__ method.") @@ -788,12 +834,7 @@ def remote(cls, *args, **kwargs): return ActorHandle -def make_actor(cls, resources, checkpoint_interval): - # Print warning if this actor requires custom resources. - for resource_name in resources: - if resource_name not in ["CPU", "GPU"]: - raise Exception("Currently only GPU resources can be used for " - "actor placement.") +def make_actor(cls, resources, checkpoint_interval, actor_method_cpus): if checkpoint_interval == 0: raise Exception("checkpoint_interval must be greater than 0.") @@ -806,13 +847,6 @@ def __ray_terminate__(self, actor_id): # remove the actor key from Redis here. ray.worker.global_worker.redis_client.hset(b"Actor:" + actor_id, "removed", True) - # Release the GPUs that this worker was using. - if len(ray.get_gpu_ids()) > 0: - release_gpus_in_use( - ray.worker.global_worker.driver_id, - ray.worker.global_worker.local_scheduler_id, - ray.get_gpu_ids(), - ray.worker.global_worker.redis_client) # Disconnect the worker from the local scheduler. The point of this # is so that when the worker kills itself below, the local # scheduler won't push an error message to the driver. @@ -899,7 +933,7 @@ def __ray_checkpoint_restore__(self): class_id = random_actor_class_id() return actor_handle_from_class(Class, class_id, resources, - checkpoint_interval) + checkpoint_interval, actor_method_cpus) ray.worker.global_worker.fetch_and_register_actor = fetch_and_register_actor diff --git a/python/ray/experimental/state.py b/python/ray/experimental/state.py --- a/python/ray/experimental/state.py +++ b/python/ray/experimental/state.py @@ -16,6 +16,8 @@ # Import flatbuffer bindings. from ray.core.generated.TaskReply import TaskReply from ray.core.generated.ResultTableReply import ResultTableReply +from ray.core.generated.TaskExecutionDependencies import \ + TaskExecutionDependencies # These prefixes must be kept up-to-date with the definitions in # ray_redis_module.cc. @@ -262,17 +264,35 @@ def _task_table(self, task_id): "ParentTaskID": binary_to_hex(task_spec.parent_task_id().id()), "ParentCounter": task_spec.parent_counter(), "ActorID": binary_to_hex(task_spec.actor_id().id()), + "ActorCreationID": + binary_to_hex(task_spec.actor_creation_id().id()), + "ActorCreationDummyObjectID": + binary_to_hex(task_spec.actor_creation_dummy_object_id().id()), "ActorCounter": task_spec.actor_counter(), "FunctionID": binary_to_hex(task_spec.function_id().id()), "Args": task_spec.arguments(), "ReturnObjectIDs": task_spec.returns(), "RequiredResources": task_spec.required_resources()} + execution_dependencies_message = ( + TaskExecutionDependencies.GetRootAsTaskExecutionDependencies( + task_table_message.ExecutionDependencies(), 0)) + execution_dependencies = [ + ray.local_scheduler.ObjectID( + execution_dependencies_message.ExecutionDependencies(i)) + for i in range( + execution_dependencies_message.ExecutionDependenciesLength())] + + # TODO(rkn): The return fields ExecutionDependenciesString and + # ExecutionDependencies are redundant, so we should remove + # ExecutionDependencies. However, it is currently used in monitor.py. + return {"State": task_table_message.State(), "LocalSchedulerID": binary_to_hex( task_table_message.LocalSchedulerId()), "ExecutionDependenciesString": task_table_message.ExecutionDependencies(), + "ExecutionDependencies": execution_dependencies, "SpillbackCount": task_table_message.SpillbackCount(), "TaskSpec": task_spec_info} diff --git a/python/ray/monitor.py b/python/ray/monitor.py --- a/python/ray/monitor.py +++ b/python/ray/monitor.py @@ -4,7 +4,6 @@ import argparse import binascii -import json import logging import os import time @@ -115,43 +114,6 @@ def subscribe(self, channel): self.subscribe_client.subscribe(channel) self.subscribed[channel] = False - def cleanup_actors(self): - """Recreate any live actors whose corresponding local scheduler died. - - For any live actor whose local scheduler just died, we choose a new - local scheduler and broadcast a notification to create that actor. - """ - actor_info = self.state.actors() - for actor_id, info in actor_info.items(): - if (not info["removed"] and - info["local_scheduler_id"] in self.dead_local_schedulers): - # Choose a new local scheduler to run the actor. - local_scheduler_id = ray.utils.select_local_scheduler( - info["driver_id"], - self.state.local_schedulers(), info["num_gpus"], - self.redis) - import sys - sys.stdout.flush() - # The new local scheduler should not be the same as the old - # local scheduler. TODO(rkn): This should not be an assert, it - # should be something more benign. - assert (binary_to_hex(local_scheduler_id) != - info["local_scheduler_id"]) - # Announce to all of the local schedulers that the actor should - # be recreated on this new local scheduler. - ray.utils.publish_actor_creation( - hex_to_binary(actor_id), - hex_to_binary(info["driver_id"]), local_scheduler_id, True, - self.redis) - log.info("Actor {} for driver {} was on dead local scheduler " - "{}. It is being recreated on local scheduler {}" - .format(actor_id, info["driver_id"], - info["local_scheduler_id"], - binary_to_hex(local_scheduler_id))) - # Update the actor info in Redis. - self.redis.hset(b"Actor:" + hex_to_binary(actor_id), - "local_scheduler_id", local_scheduler_id) - def cleanup_task_table(self): """Clean up global state for failed local schedulers. @@ -473,58 +435,8 @@ def driver_removed_handler(self, unused_channel, data): log.info( "Driver {} has been removed.".format(binary_to_hex(driver_id))) - # Get a list of the local schedulers that have not been deleted. - local_schedulers = ray.global_state.local_schedulers() - self._clean_up_entries_for_driver(driver_id) - # Release any GPU resources that have been reserved for this driver in - # Redis. - for local_scheduler in local_schedulers: - if local_scheduler.get("GPU", 0) > 0: - local_scheduler_id = local_scheduler["DBClientID"] - - num_gpus_returned = 0 - - # Perform a transaction to return the GPUs. - with self.redis.pipeline() as pipe: - while True: - try: - # If this key is changed before the transaction - # below (the multi/exec block), then the - # transaction will not take place. - pipe.watch(local_scheduler_id) - - result = pipe.hget(local_scheduler_id, - "gpus_in_use") - gpus_in_use = (dict() if result is None else - json.loads(result.decode("ascii"))) - - driver_id_hex = binary_to_hex(driver_id) - if driver_id_hex in gpus_in_use: - num_gpus_returned = gpus_in_use.pop( - driver_id_hex) - - pipe.multi() - - pipe.hset(local_scheduler_id, "gpus_in_use", - json.dumps(gpus_in_use)) - - pipe.execute() - # If a WatchError is not raise, then the operations - # should have gone through atomically. - break - except redis.WatchError: - # Another client must have changed the watched key - # between the time we started WATCHing it and the - # pipeline's execution. We should just retry. - continue - - log.info("Driver {} is returning GPU IDs {} to local " - "scheduler {}.".format( - binary_to_hex(driver_id), num_gpus_returned, - local_scheduler_id)) - def process_messages(self): """Process all messages ready in the subscription channels. @@ -592,7 +504,6 @@ def run(self): # state in the state tables. if len(self.dead_local_schedulers) > 0: self.cleanup_task_table() - self.cleanup_actors() if len(self.dead_plasma_managers) > 0: self.cleanup_object_table() log.debug("{} dead local schedulers, {} plasma managers total, {} " @@ -617,7 +528,6 @@ def run(self): # dead in this round, clean up the associated state. if len(self.dead_local_schedulers) > num_dead_local_schedulers: self.cleanup_task_table() - self.cleanup_actors() if len(self.dead_plasma_managers) > num_dead_plasma_managers: self.cleanup_object_table() diff --git a/python/ray/tune/registry.py b/python/ray/tune/registry.py --- a/python/ray/tune/registry.py +++ b/python/ray/tune/registry.py @@ -7,9 +7,7 @@ import numpy as np import ray -from ray.tune import TuneError from ray.local_scheduler import ObjectID -from ray.tune.trainable import Trainable, wrap_function TRAINABLE_CLASS = "trainable_class" ENV_CREATOR = "env_creator" @@ -29,6 +27,8 @@ def register_trainable(name, trainable): automatically converted into a class during registration. """ + from ray.tune.trainable import Trainable, wrap_function + if isinstance(trainable, FunctionType): trainable = wrap_function(trainable) if not issubclass(trainable, Trainable): @@ -83,6 +83,7 @@ def __init__(self, objs=None): def register(self, category, key, value): if category not in KNOWN_CATEGORIES: + from ray.tune import TuneError raise TuneError("Unknown category {} not among {}".format( category, KNOWN_CATEGORIES)) self._all_objects[(category, key)] = value diff --git a/python/ray/tune/trial.py b/python/ray/tune/trial.py --- a/python/ray/tune/trial.py +++ b/python/ray/tune/trial.py @@ -12,7 +12,10 @@ from ray.tune import TuneError from ray.tune.logger import NoopLogger, UnifiedLogger, pretty_print -from ray.tune.registry import _default_registry, get_registry, TRAINABLE_CLASS +# NOTE(rkn): We import ray.tune.registry here instead of importing the names we +# need because there are cyclic imports that may cause specific names to not +# have been defined yet. See https://github.com/ray-project/ray/issues/1716. +import ray.tune.registry from ray.tune.result import TrainingResult, DEFAULT_RESULTS_DIR from ray.utils import random_string, binary_to_hex @@ -85,8 +88,8 @@ def __init__( in ray.tune.config_parser. """ - if not _default_registry.contains( - TRAINABLE_CLASS, trainable_name): + if not ray.tune.registry._default_registry.contains( + ray.tune.registry.TRAINABLE_CLASS, trainable_name): raise TuneError("Unknown trainable: " + trainable_name) if stopping_criterion: @@ -341,8 +344,8 @@ def update_last_result(self, result, terminate=False): def _setup_runner(self): self.status = Trial.RUNNING - trainable_cls = get_registry().get( - TRAINABLE_CLASS, self.trainable_name) + trainable_cls = ray.tune.registry.get_registry().get( + ray.tune.registry.TRAINABLE_CLASS, self.trainable_name) cls = ray.remote( num_cpus=self.resources.driver_cpu_limit, num_gpus=self.resources.driver_gpu_limit)(trainable_cls) @@ -367,7 +370,7 @@ def logger_creator(config): # Logging for trials is handled centrally by TrialRunner, so # configure the remote runner to use a noop-logger. self.runner = cls.remote( - config=self.config, registry=get_registry(), + config=self.config, registry=ray.tune.registry.get_registry(), logger_creator=logger_creator) def set_verbose(self, verbose): diff --git a/python/ray/utils.py b/python/ray/utils.py --- a/python/ray/utils.py +++ b/python/ray/utils.py @@ -4,10 +4,8 @@ import binascii import collections -import json import numpy as np import os -import redis import sys import ray.local_scheduler @@ -162,192 +160,3 @@ def set_cuda_visible_devices(gpu_ids): gpu_ids: This is a list of integers representing GPU IDs. """ os.environ["CUDA_VISIBLE_DEVICES"] = ",".join([str(i) for i in gpu_ids]) - - -def attempt_to_reserve_gpus(num_gpus, driver_id, local_scheduler, - redis_client): - """Attempt to acquire GPUs on a particular local scheduler for an actor. - - Args: - num_gpus: The number of GPUs to acquire. - driver_id: The ID of the driver responsible for creating the actor. - local_scheduler: Information about the local scheduler. - redis_client: The redis client to use for interacting with Redis. - - Returns: - True if the GPUs were successfully reserved and false otherwise. - """ - assert num_gpus != 0 - local_scheduler_id = local_scheduler["DBClientID"] - local_scheduler_total_gpus = int(local_scheduler["GPU"]) - - success = False - - # Attempt to acquire GPU IDs atomically. - with redis_client.pipeline() as pipe: - while True: - try: - # If this key is changed before the transaction below (the - # multi/exec block), then the transaction will not take place. - pipe.watch(local_scheduler_id) - - # Figure out which GPUs are currently in use. - result = redis_client.hget(local_scheduler_id, "gpus_in_use") - gpus_in_use = dict() if result is None else json.loads( - result.decode("ascii")) - num_gpus_in_use = 0 - for key in gpus_in_use: - num_gpus_in_use += gpus_in_use[key] - assert num_gpus_in_use <= local_scheduler_total_gpus - - pipe.multi() - - if local_scheduler_total_gpus - num_gpus_in_use >= num_gpus: - # There are enough available GPUs, so try to reserve some. - # We use the hex driver ID in hex as a dictionary key so - # that the dictionary is JSON serializable. - driver_id_hex = binary_to_hex(driver_id) - if driver_id_hex not in gpus_in_use: - gpus_in_use[driver_id_hex] = 0 - gpus_in_use[driver_id_hex] += num_gpus - - # Stick the updated GPU IDs back in Redis - pipe.hset(local_scheduler_id, "gpus_in_use", - json.dumps(gpus_in_use)) - success = True - - pipe.execute() - # If a WatchError is not raised, then the operations should - # have gone through atomically. - break - except redis.WatchError: - # Another client must have changed the watched key between the - # time we started WATCHing it and the pipeline's execution. We - # should just retry. - success = False - continue - - return success - - -def release_gpus_in_use(driver_id, local_scheduler_id, gpu_ids, redis_client): - """Release the GPUs that a given worker was using. - - Note that this does not affect the local scheduler's bookkeeping. It only - affects the GPU allocations which are recorded in the primary Redis shard, - which are redundant with the local scheduler bookkeeping. - - Args: - driver_id: The ID of the driver that is releasing some GPUs. - local_scheduler_id: The ID of the local scheduler that owns the GPUs - being released. - gpu_ids: The IDs of the GPUs being released. - redis_client: A client for the primary Redis shard. - """ - # Attempt to release GPU IDs atomically. - with redis_client.pipeline() as pipe: - while True: - try: - # If this key is changed before the transaction below (the - # multi/exec block), then the transaction will not take place. - pipe.watch(local_scheduler_id) - - # Figure out which GPUs are currently in use. - result = redis_client.hget(local_scheduler_id, "gpus_in_use") - gpus_in_use = dict() if result is None else json.loads( - result.decode("ascii")) - - assert driver_id in gpus_in_use - assert gpus_in_use[driver_id] >= len(gpu_ids) - - gpus_in_use[driver_id] -= len(gpu_ids) - - pipe.multi() - - pipe.hset(local_scheduler_id, "gpus_in_use", - json.dumps(gpus_in_use)) - - pipe.execute() - # If a WatchError is not raised, then the operations should - # have gone through atomically. - break - except redis.WatchError: - # Another client must have changed the watched key between the - # time we started WATCHing it and the pipeline's execution. We - # should just retry. - continue - - -def select_local_scheduler(driver_id, local_schedulers, num_gpus, - redis_client): - """Select a local scheduler to assign this actor to. - - Args: - driver_id: The ID of the driver who the actor is for. - local_schedulers: A list of dictionaries of information about the local - schedulers. - num_gpus (int): The number of GPUs that must be reserved for this - actor. - redis_client: The Redis client to use for interacting with Redis. - - Returns: - The ID of the local scheduler that has been chosen. - - Raises: - Exception: An exception is raised if no local scheduler can be found - with sufficient resources. - """ - local_scheduler_id = None - # Loop through all of the local schedulers in a random order. - local_schedulers = np.random.permutation(local_schedulers) - for local_scheduler in local_schedulers: - if local_scheduler["CPU"] < 1: - continue - if local_scheduler.get("GPU", 0) < num_gpus: - continue - if num_gpus == 0: - local_scheduler_id = hex_to_binary(local_scheduler["DBClientID"]) - break - else: - # Try to reserve enough GPUs on this local scheduler. - success = attempt_to_reserve_gpus(num_gpus, driver_id, - local_scheduler, redis_client) - if success: - local_scheduler_id = hex_to_binary( - local_scheduler["DBClientID"]) - break - - if local_scheduler_id is None: - raise Exception("Could not find a node with enough GPUs or other " - "resources to create this actor. The local scheduler " - "information is {}.".format(local_schedulers)) - - return local_scheduler_id - - -def publish_actor_creation(actor_id, driver_id, local_scheduler_id, - reconstruct, redis_client): - """Publish a notification that an actor should be created. - - This broadcast will be received by all of the local schedulers. The local - scheduler whose ID is being broadcast will create the actor. Any other - local schedulers that have already created the actor will kill it. All - local schedulers will update their internal data structures to redirect - tasks for this actor to the new local scheduler. - - Args: - actor_id: The ID of the actor involved. - driver_id: The ID of the driver responsible for the actor. - local_scheduler_id: The ID of the local scheduler that is suposed to - create the actor. - reconstruct: True if the actor should be created in "reconstruct" mode. - redis_client: The client used to interact with Redis. - """ - reconstruct_bit = b"1" if reconstruct else b"0" - # Really we should encode this message as a flatbuffer object. However, - # we're having trouble getting that to work. It almost works, but in Python - # 2.7, builder.CreateString fails on byte strings that contain characters - # outside range(128). - redis_client.publish("actor_notifications", - actor_id + driver_id + local_scheduler_id + - reconstruct_bit) diff --git a/python/ray/worker.py b/python/ray/worker.py --- a/python/ray/worker.py +++ b/python/ray/worker.py @@ -49,6 +49,7 @@ NIL_LOCAL_SCHEDULER_ID = NIL_ID NIL_FUNCTION_ID = NIL_ID NIL_ACTOR_ID = NIL_ID +NIL_ACTOR_HANDLE_ID = NIL_ID # This must be kept in sync with the `error_types` array in # common/state/error_table.h. @@ -58,6 +59,19 @@ # This must be kept in sync with the `scheduling_state` enum in common/task.h. TASK_STATUS_RUNNING = 8 +# Default resource requirements for remote functions. +DEFAULT_REMOTE_FUNCTION_CPUS = 1 +DEFAULT_REMOTE_FUNCTION_GPUS = 0 +# Default resource requirements for actors when no resource requirements are +# specified. +DEFAULT_ACTOR_METHOD_CPUS_SIMPLE_CASE = 1 +DEFAULT_ACTOR_CREATION_CPUS_SIMPLE_CASE = 0 +# Default resource requirements for actors when some resource requirements are +# specified. +DEFAULT_ACTOR_METHOD_CPUS_SPECIFIED_CASE = 0 +DEFAULT_ACTOR_CREATION_CPUS_SPECIFIED_CASE = 1 +DEFAULT_ACTOR_CREATION_GPUS_SPECIFIED_CASE = 0 + class FunctionID(object): def __init__(self, function_id): @@ -222,6 +236,10 @@ def __init__(self): self.make_actor = None self.actors = {} self.actor_task_counter = 0 + # A set of all of the actor class keys that have been imported by the + # import thread. It is safe to convert this worker into an actor of + # these types. + self.imported_actor_classes = set() # The number of threads Plasma should use when putting an object in the # object store. self.memcopy_threads = 12 @@ -358,7 +376,8 @@ def put_object(self, object_id, value): # and make sure that the objects are in fact the same. We also # should return an error code to the caller instead of printing a # message. - print("This object already exists in the object store.") + print("The object with ID {} already exists in the object store." + .format(object_id)) def retrieve_and_deserialize(self, object_ids, timeout, error_timeout=10): start_time = time.time() @@ -485,7 +504,8 @@ def get_object(self, object_ids): def submit_task(self, function_id, args, actor_id=None, actor_handle_id=None, actor_counter=0, - is_actor_checkpoint_method=False, + is_actor_checkpoint_method=False, actor_creation_id=None, + actor_creation_dummy_object_id=None, execution_dependencies=None): """Submit a remote task to the scheduler. @@ -502,15 +522,33 @@ def submit_task(self, function_id, args, actor_id=None, actor_counter: The counter of the actor task. is_actor_checkpoint_method: True if this is an actor checkpoint task and false otherwise. + actor_creation_id: The ID of the actor to create, if this is an + actor creation task. + actor_creation_dummy_object_id: If this task is an actor method, + then this argument is the dummy object ID associated with the + actor creation task for the corresponding actor. + execution_dependencies: The execution dependencies for this task. + + Returns: + The return object IDs for this task. """ with log_span("ray:submit_task", worker=self): check_main_thread() if actor_id is None: assert actor_handle_id is None actor_id = ray.local_scheduler.ObjectID(NIL_ACTOR_ID) - actor_handle_id = ray.local_scheduler.ObjectID(NIL_ACTOR_ID) + actor_handle_id = ray.local_scheduler.ObjectID( + NIL_ACTOR_HANDLE_ID) else: assert actor_handle_id is not None + + if actor_creation_id is None: + actor_creation_id = ray.local_scheduler.ObjectID(NIL_ACTOR_ID) + + if actor_creation_dummy_object_id is None: + actor_creation_dummy_object_id = ( + ray.local_scheduler.ObjectID(NIL_ID)) + # Put large or complex arguments that are passed by value in the # object store first. args_for_local_scheduler = [] @@ -541,6 +579,8 @@ def submit_task(self, function_id, args, actor_id=None, function_properties.num_return_vals, self.current_task_id, self.task_index, + actor_creation_id, + actor_creation_dummy_object_id, actor_id, actor_handle_id, actor_counter, @@ -801,6 +841,29 @@ def _handle_process_task_failure(self, function_id, return_object_ids, data={"function_id": function_id.id(), "function_name": function_name}) + def _become_actor(self, task): + """Turn this worker into an actor. + + Args: + task: The actor creation task. + """ + assert self.actor_id == NIL_ACTOR_ID + arguments = task.arguments() + assert len(arguments) == 1 + self.actor_id = task.actor_creation_id().id() + class_id = arguments[0] + + key = b"ActorClass:" + class_id + + # Wait for the actor class key to have been imported by the import + # thread. TODO(rkn): It shouldn't be possible to end up in an infinite + # loop here, but we should push an error to the driver if too much time + # is spent here. + while key not in self.imported_actor_classes: + time.sleep(0.001) + + self.fetch_and_register_actor(key, task.required_resources(), self) + def _wait_for_and_process_task(self, task): """Wait for a task to be ready and process the task. @@ -808,6 +871,14 @@ def _wait_for_and_process_task(self, task): task: The task to execute. """ function_id = task.function_id() + + # TODO(rkn): It would be preferable for actor creation tasks to share + # more of the code path with regular task execution. + if (task.actor_creation_id() != + ray.local_scheduler.ObjectID(NIL_ACTOR_ID)): + self._become_actor(task) + return + # Wait until the function to be executed has actually been registered # on this worker. We will push warnings to the user if we spend too # long in this loop. @@ -1379,7 +1450,7 @@ def _init(address_info=None, address_info["local_scheduler_socket_names"][0]), "webui_url": address_info["webui_url"]} connect(driver_address_info, object_id_seed=object_id_seed, - mode=driver_mode, worker=global_worker, actor_id=NIL_ACTOR_ID) + mode=driver_mode, worker=global_worker) return address_info @@ -1678,13 +1749,10 @@ def import_thread(worker, mode): elif key.startswith(b"FunctionsToRun"): fetch_and_execute_function_to_run(key, worker=worker) elif key.startswith(b"ActorClass"): - # If this worker is an actor that is supposed to construct this - # class, fetch the actor and class information and construct - # the class. - class_id = key.split(b":", 1)[1] - if (worker.actor_id != NIL_ACTOR_ID and - worker.class_id == class_id): - worker.fetch_and_register_actor(key, worker) + # Keep track of the fact that this actor class has been + # exported so that we know it is safe to turn this worker into + # an actor of that class. + worker.imported_actor_classes.add(key) else: raise Exception("This code should be unreachable.") @@ -1721,12 +1789,14 @@ def import_thread(worker, mode): worker=worker): fetch_and_execute_function_to_run(key, worker=worker) - elif key.startswith(b"Actor"): - # Only get the actor if the actor ID matches the actor - # ID of this worker. - actor_id, = worker.redis_client.hmget(key, "actor_id") - if worker.actor_id == actor_id: - worker.fetch_and_register["Actor"](key, worker) + elif key.startswith(b"ActorClass"): + # Keep track of the fact that this actor class has been + # exported so that we know it is safe to turn this + # worker into an actor of that class. + worker.imported_actor_classes.add(key) + + # TODO(rkn): We may need to bring back the case of fetching + # actor classes here. else: raise Exception("This code should be unreachable.") except redis.ConnectionError: @@ -1735,8 +1805,7 @@ def import_thread(worker, mode): pass -def connect(info, object_id_seed=None, mode=WORKER_MODE, worker=global_worker, - actor_id=NIL_ACTOR_ID): +def connect(info, object_id_seed=None, mode=WORKER_MODE, worker=global_worker): """Connect this worker to the local scheduler, to Plasma, and to Redis. Args: @@ -1746,8 +1815,6 @@ def connect(info, object_id_seed=None, mode=WORKER_MODE, worker=global_worker, deterministic. mode: The mode of the worker. One of SCRIPT_MODE, WORKER_MODE, PYTHON_MODE, and SILENT_MODE. - actor_id: The ID of the actor running on this worker. If this worker is - not an actor, then this is NIL_ACTOR_ID. """ check_main_thread() # Do some basic checking to make sure we didn't call ray.init twice. @@ -1757,7 +1824,9 @@ def connect(info, object_id_seed=None, mode=WORKER_MODE, worker=global_worker, assert worker.cached_remote_functions_and_actors is not None, error_message # Initialize some fields. worker.worker_id = random_string() - worker.actor_id = actor_id + # All workers start out as non-actors. A worker can be turned into an actor + # after it is created. + worker.actor_id = NIL_ACTOR_ID worker.connected = True worker.set_mode(mode) # The worker.events field is used to aggregate logging information and @@ -1854,15 +1923,8 @@ def connect(info, object_id_seed=None, mode=WORKER_MODE, worker=global_worker, worker.plasma_client = plasma.connect(info["store_socket_name"], info["manager_socket_name"], 64) - # Create the local scheduler client. - if worker.actor_id != NIL_ACTOR_ID: - num_gpus = int(worker.redis_client.hget(b"Actor:" + actor_id, - "num_gpus")) - else: - num_gpus = 0 worker.local_scheduler_client = ray.local_scheduler.LocalSchedulerClient( - info["local_scheduler_socket_name"], worker.worker_id, worker.actor_id, - is_worker, num_gpus) + info["local_scheduler_socket_name"], worker.worker_id, is_worker) # If this is a driver, set the current task ID, the task driver ID, and set # the task index to 0. @@ -1906,6 +1968,8 @@ def connect(info, object_id_seed=None, mode=WORKER_MODE, worker=global_worker, worker.task_index, ray.local_scheduler.ObjectID(NIL_ACTOR_ID), ray.local_scheduler.ObjectID(NIL_ACTOR_ID), + ray.local_scheduler.ObjectID(NIL_ACTOR_ID), + ray.local_scheduler.ObjectID(NIL_ACTOR_ID), nil_actor_counter, False, [], @@ -1923,12 +1987,6 @@ def connect(info, object_id_seed=None, mode=WORKER_MODE, worker=global_worker, # driver task. worker.current_task_id = driver_task.task_id() - # If this is an actor, get the ID of the corresponding class for the actor. - if worker.actor_id != NIL_ACTOR_ID: - actor_key = b"Actor:" + worker.actor_id - class_id = worker.redis_client.hget(actor_key, "class_id") - worker.class_id = class_id - # Initialize the serialization library. This registers some classes, and so # it must be run before we export all of the cached remote functions. _initialize_serialization() @@ -2457,10 +2515,16 @@ def remote(*args, **kwargs): """ worker = global_worker - def make_remote_decorator(num_return_vals, resources, max_calls, - checkpoint_interval, func_id=None): + def make_remote_decorator(num_return_vals, num_cpus, num_gpus, resources, + max_calls, checkpoint_interval, func_id=None): def remote_decorator(func_or_class): if inspect.isfunction(func_or_class) or is_cython(func_or_class): + # Set the remote function default resources. + resources["CPU"] = (DEFAULT_REMOTE_FUNCTION_CPUS + if num_cpus is None else num_cpus) + resources["GPU"] = (DEFAULT_REMOTE_FUNCTION_GPUS + if num_gpus is None else num_gpus) + function_properties = FunctionProperties( num_return_vals=num_return_vals, resources=resources, @@ -2468,8 +2532,28 @@ def remote_decorator(func_or_class): return remote_function_decorator(func_or_class, function_properties) if inspect.isclass(func_or_class): + # Set the actor default resources. + if num_cpus is None and num_gpus is None and resources == {}: + # In the default case, actors acquire no resources for + # their lifetime, and actor methods will require 1 CPU. + resources["CPU"] = DEFAULT_ACTOR_CREATION_CPUS_SIMPLE_CASE + actor_method_cpus = DEFAULT_ACTOR_METHOD_CPUS_SIMPLE_CASE + else: + # If any resources are specified, then all resources are + # acquired for the actor's lifetime and no resources are + # associated with methods. + resources["CPU"] = ( + DEFAULT_ACTOR_CREATION_CPUS_SPECIFIED_CASE + if num_cpus is None else num_cpus) + resources["GPU"] = ( + DEFAULT_ACTOR_CREATION_GPUS_SPECIFIED_CASE + if num_gpus is None else num_gpus) + actor_method_cpus = ( + DEFAULT_ACTOR_METHOD_CPUS_SPECIFIED_CASE) + return worker.make_actor(func_or_class, resources, - checkpoint_interval) + checkpoint_interval, + actor_method_cpus) raise Exception("The @ray.remote decorator must be applied to " "either a function or to a class.") @@ -2535,8 +2619,8 @@ def func_invoker(*args, **kwargs): return remote_decorator # Handle resource arguments - num_cpus = kwargs["num_cpus"] if "num_cpus" in kwargs else 1 - num_gpus = kwargs["num_gpus"] if "num_gpus" in kwargs else 0 + num_cpus = kwargs["num_cpus"] if "num_cpus" in kwargs else None + num_gpus = kwargs["num_gpus"] if "num_gpus" in kwargs else None resources = kwargs.get("resources", {}) if not isinstance(resources, dict): raise Exception("The 'resources' keyword argument must be a " @@ -2544,8 +2628,6 @@ def func_invoker(*args, **kwargs): .format(type(resources))) assert "CPU" not in resources, "Use the 'num_cpus' argument." assert "GPU" not in resources, "Use the 'num_gpus' argument." - resources["CPU"] = num_cpus - resources["GPU"] = num_gpus # Handle other arguments. num_return_vals = (kwargs["num_return_vals"] if "num_return_vals" in kwargs else 1) @@ -2556,13 +2638,14 @@ def func_invoker(*args, **kwargs): if _mode() == WORKER_MODE: if "function_id" in kwargs: function_id = kwargs["function_id"] - return make_remote_decorator(num_return_vals, resources, max_calls, + return make_remote_decorator(num_return_vals, num_cpus, num_gpus, + resources, max_calls, checkpoint_interval, function_id) if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # This is the case where the decorator is just @ray.remote. return make_remote_decorator( - num_return_vals, resources, + num_return_vals, num_cpus, num_gpus, resources, max_calls, checkpoint_interval)(args[0]) else: # This is the case where the decorator is something like @@ -2580,5 +2663,5 @@ def func_invoker(*args, **kwargs): "resources", "max_calls", "checkpoint_interval"], error_string assert "function_id" not in kwargs - return make_remote_decorator(num_return_vals, resources, max_calls, - checkpoint_interval) + return make_remote_decorator(num_return_vals, num_cpus, num_gpus, + resources, max_calls, checkpoint_interval) diff --git a/python/ray/workers/default_worker.py b/python/ray/workers/default_worker.py --- a/python/ray/workers/default_worker.py +++ b/python/ray/workers/default_worker.py @@ -3,7 +3,6 @@ from __future__ import print_function import argparse -import binascii import traceback import ray @@ -21,32 +20,18 @@ help="the object store manager's name") parser.add_argument("--local-scheduler-name", required=True, type=str, help="the local scheduler's name") -parser.add_argument("--actor-id", required=False, type=str, - help="the actor ID of this worker") -parser.add_argument("--reconstruct", action="store_true", - help=("true if the actor should be started in reconstruct " - "mode")) if __name__ == "__main__": args = parser.parse_args() - # If this worker is not an actor, it cannot be started in reconstruct mode. - if args.actor_id is None: - assert not args.reconstruct - info = {"node_ip_address": args.node_ip_address, "redis_address": args.redis_address, "store_socket_name": args.object_store_name, "manager_socket_name": args.object_store_manager_name, "local_scheduler_socket_name": args.local_scheduler_name} - if args.actor_id is not None: - actor_id = binascii.unhexlify(args.actor_id) - else: - actor_id = ray.worker.NIL_ACTOR_ID - - ray.worker.connect(info, mode=ray.WORKER_MODE, actor_id=actor_id) + ray.worker.connect(info, mode=ray.WORKER_MODE) error_explanation = """ This error is unexpected and should not have happened. Somehow a worker
[tune] ImportError: cannot import name '_default_registry' I'm seeing this on a development branch, but I suspect it could occur more generally. It occurs every once in a while when running ``` python python/ray/tune/test/trial_runner_test.py ``` The error is ``` Traceback (most recent call last): File "/home/ubuntu/ray/python/ray/worker.py", line 1694, in fetch_and_execute_function_to_run function = pickle.loads(serialized_function) File "/home/ubuntu/ray/python/ray/tune/registry.py", line 12, in <module> from ray.tune.trainable import Trainable, wrap_function File "/home/ubuntu/ray/python/ray/tune/__init__.py", line 6, in <module> from ray.tune.tune import run_experiments File "/home/ubuntu/ray/python/ray/tune/tune.py", line 8, in <module> from ray.tune.hyperband import HyperBandScheduler File "/home/ubuntu/ray/python/ray/tune/hyperband.py", line 8, in <module> from ray.tune.trial_scheduler import FIFOScheduler, TrialScheduler File "/home/ubuntu/ray/python/ray/tune/trial_scheduler.py", line 5, in <module> from ray.tune.trial import Trial File "/home/ubuntu/ray/python/ray/tune/trial.py", line 15, in <module> from ray.tune.registry import _default_registry, get_registry, TRAINABLE_CLASS ImportError: cannot import name '_default_registry' ``` It looks to me like the issue is some circular imports. `registry` imports `tune`, which imports `hyperband`, which imports `trial_scheduler`, which imports `trial`, which imports `_default_registry` from `registry`. The problem is that this is all triggered by the `import registry` command which hasn't defined `_default_registry` yet because it's defined at the end of the file... somehow we need to break this cyclic import. One solution mentioned by @ericl is to make one of the imports lazy.
2018-03-07T07:57:13Z
[]
[]
Traceback (most recent call last): File "/home/ubuntu/ray/python/ray/worker.py", line 1694, in fetch_and_execute_function_to_run function = pickle.loads(serialized_function) File "/home/ubuntu/ray/python/ray/tune/registry.py", line 12, in <module> from ray.tune.trainable import Trainable, wrap_function File "/home/ubuntu/ray/python/ray/tune/__init__.py", line 6, in <module> from ray.tune.tune import run_experiments File "/home/ubuntu/ray/python/ray/tune/tune.py", line 8, in <module> from ray.tune.hyperband import HyperBandScheduler File "/home/ubuntu/ray/python/ray/tune/hyperband.py", line 8, in <module> from ray.tune.trial_scheduler import FIFOScheduler, TrialScheduler File "/home/ubuntu/ray/python/ray/tune/trial_scheduler.py", line 5, in <module> from ray.tune.trial import Trial File "/home/ubuntu/ray/python/ray/tune/trial.py", line 15, in <module> from ray.tune.registry import _default_registry, get_registry, TRAINABLE_CLASS ImportError: cannot import name '_default_registry'
17,756
ray-project/ray
ray-project__ray-1774
8704c8618c8d0115c5b0f6393f78858ee5af8702
diff --git a/python/ray/rllib/agent.py b/python/ray/rllib/agent.py --- a/python/ray/rllib/agent.py +++ b/python/ray/rllib/agent.py @@ -220,7 +220,7 @@ def _train(self): def get_agent_class(alg): - """Returns the class of an known agent given its name.""" + """Returns the class of a known agent given its name.""" if alg == "PPO": from ray.rllib import ppo diff --git a/python/ray/rllib/es/es.py b/python/ray/rllib/es/es.py --- a/python/ray/rllib/es/es.py +++ b/python/ray/rllib/es/es.py @@ -12,14 +12,12 @@ import time import ray -from ray.rllib.agent import Agent -from ray.rllib.models import ModelCatalog +from ray.rllib import agent from ray.rllib.es import optimizers from ray.rllib.es import policies from ray.rllib.es import tabular_logger as tlogger from ray.rllib.es import utils -from ray.tune.result import TrainingResult Result = namedtuple("Result", [ @@ -72,7 +70,9 @@ def __init__(self, registry, config, policy_params, env_creator, noise, self.noise = SharedNoiseTable(noise) self.env = env_creator(config["env_config"]) - self.preprocessor = ModelCatalog.get_preprocessor(registry, self.env) + from ray.rllib import models + self.preprocessor = models.ModelCatalog.get_preprocessor( + registry, self.env) self.sess = utils.make_session(single_threaded=True) self.policy = policies.GenericPolicy( @@ -133,7 +133,7 @@ def do_rollouts(self, params, timestep_limit=None): eval_lengths=eval_lengths) -class ESAgent(Agent): +class ESAgent(agent.Agent): _agent_name = "ES" _default_config = DEFAULT_CONFIG _allow_unknown_subkeys = ["env_config"] @@ -144,7 +144,9 @@ def _init(self): } env = self.env_creator(self.config["env_config"]) - preprocessor = ModelCatalog.get_preprocessor(self.registry, env) + from ray.rllib import models + preprocessor = models.ModelCatalog.get_preprocessor( + self.registry, env) self.sess = utils.make_session(single_threaded=False) self.policy = policies.GenericPolicy( @@ -292,7 +294,7 @@ def _train(self): "time_elapsed": step_tend - self.tstart } - result = TrainingResult( + result = ray.tune.result.TrainingResult( episode_reward_mean=eval_returns.mean(), episode_len_mean=eval_lengths.mean(), timesteps_this_iter=noisy_lengths.sum(),
[rllib] Deadlock error when running ES. When running ``` python ray/python/ray/rllib/train.py --redis-address=172.31.7.72:6379 --env=Humanoid-v1 --run=ES --config='{"episodes_per_batch": 1000, "timesteps_per_batch": 10000, "num_workers": 400}' ``` on a cluster (100 machines), I see ``` Traceback (most recent call last): File "/home/ubuntu/ray/python/ray/worker.py", line 1720, in fetch_and_execute_function_to_run function = pickle.loads(serialized_function) File "/home/ubuntu/ray/python/ray/rllib/__init__.py", line 17, in <module> _register_all() File "/home/ubuntu/ray/python/ray/rllib/__init__.py", line 14, in _register_all register_trainable(key, get_agent_class(key)) File "/home/ubuntu/ray/python/ray/rllib/agent.py", line 229, in get_agent_class from ray.rllib import es File "/home/ubuntu/ray/python/ray/rllib/es/__init__.py", line 1, in <module> from ray.rllib.es.es import (ESAgent, DEFAULT_CONFIG) File "/home/ubuntu/ray/python/ray/rllib/es/es.py", line 19, in <module> from ray.rllib.es import policies File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 168, in __enter__ File "<frozen importlib._bootstrap>", line 110, in acquire _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('ray.rllib.es.policies') at 139937598221224 ``` This likely has to do with recursive imports in rllib, probably related to #1716.
2018-03-23T01:26:00Z
[]
[]
Traceback (most recent call last): File "/home/ubuntu/ray/python/ray/worker.py", line 1720, in fetch_and_execute_function_to_run function = pickle.loads(serialized_function) File "/home/ubuntu/ray/python/ray/rllib/__init__.py", line 17, in <module> _register_all() File "/home/ubuntu/ray/python/ray/rllib/__init__.py", line 14, in _register_all register_trainable(key, get_agent_class(key)) File "/home/ubuntu/ray/python/ray/rllib/agent.py", line 229, in get_agent_class from ray.rllib import es File "/home/ubuntu/ray/python/ray/rllib/es/__init__.py", line 1, in <module> from ray.rllib.es.es import (ESAgent, DEFAULT_CONFIG) File "/home/ubuntu/ray/python/ray/rllib/es/es.py", line 19, in <module> from ray.rllib.es import policies File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 168, in __enter__ File "<frozen importlib._bootstrap>", line 110, in acquire _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('ray.rllib.es.policies') at 139937598221224
17,760
ray-project/ray
ray-project__ray-1783
0fd4112354d433105a8945f51ffc2b25db16d169
diff --git a/python/ray/worker.py b/python/ray/worker.py --- a/python/ray/worker.py +++ b/python/ray/worker.py @@ -881,7 +881,8 @@ def _become_actor(self, task): while key not in self.imported_actor_classes: time.sleep(0.001) - self.fetch_and_register_actor(key, task.required_resources(), self) + with self.lock: + self.fetch_and_register_actor(key, task.required_resources(), self) def _wait_for_and_process_task(self, task): """Wait for a task to be ready and process the task.
[rllib] Deadlock error when running ES. When running ``` python ray/python/ray/rllib/train.py --redis-address=172.31.7.72:6379 --env=Humanoid-v1 --run=ES --config='{"episodes_per_batch": 1000, "timesteps_per_batch": 10000, "num_workers": 400}' ``` on a cluster (100 machines), I see ``` Traceback (most recent call last): File "/home/ubuntu/ray/python/ray/worker.py", line 1720, in fetch_and_execute_function_to_run function = pickle.loads(serialized_function) File "/home/ubuntu/ray/python/ray/rllib/__init__.py", line 17, in <module> _register_all() File "/home/ubuntu/ray/python/ray/rllib/__init__.py", line 14, in _register_all register_trainable(key, get_agent_class(key)) File "/home/ubuntu/ray/python/ray/rllib/agent.py", line 229, in get_agent_class from ray.rllib import es File "/home/ubuntu/ray/python/ray/rllib/es/__init__.py", line 1, in <module> from ray.rllib.es.es import (ESAgent, DEFAULT_CONFIG) File "/home/ubuntu/ray/python/ray/rllib/es/es.py", line 19, in <module> from ray.rllib.es import policies File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 168, in __enter__ File "<frozen importlib._bootstrap>", line 110, in acquire _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('ray.rllib.es.policies') at 139937598221224 ``` This likely has to do with recursive imports in rllib, probably related to #1716.
The same happens with PPO: ``` File "/opt/conda/lib/python3.6/site-packages/ray/actor.py", line 284, in fetch_and_register_actor unpickled_class = pickle.loads(pickled_class) File "/opt/conda/lib/python3.6/site-packages/ray/rllib/ppo/__init__.py", line 1, in <module> from ray.rllib.ppo.ppo import (PPOAgent, DEFAULT_CONFIG) File "/opt/conda/lib/python3.6/site-packages/ray/rllib/ppo/ppo.py", line 17, in <module> from ray.rllib.ppo.ppo_evaluator import PPOEvaluator File "/opt/conda/lib/python3.6/site-packages/ray/rllib/ppo/ppo_evaluator.py", line 14, in <module> from ray.rllib.optimizers import PolicyEvaluator, SampleBatch File "<frozen importlib._bootstrap>", line 960, in _find_and_load File "<frozen importlib._bootstrap>", line 151, in __enter__ File "<frozen importlib._bootstrap>", line 93, in acquire _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('ray.rllib.optimizers') at 140202634781472```
2018-03-26T23:05:26Z
[]
[]
Traceback (most recent call last): File "/home/ubuntu/ray/python/ray/worker.py", line 1720, in fetch_and_execute_function_to_run function = pickle.loads(serialized_function) File "/home/ubuntu/ray/python/ray/rllib/__init__.py", line 17, in <module> _register_all() File "/home/ubuntu/ray/python/ray/rllib/__init__.py", line 14, in _register_all register_trainable(key, get_agent_class(key)) File "/home/ubuntu/ray/python/ray/rllib/agent.py", line 229, in get_agent_class from ray.rllib import es File "/home/ubuntu/ray/python/ray/rllib/es/__init__.py", line 1, in <module> from ray.rllib.es.es import (ESAgent, DEFAULT_CONFIG) File "/home/ubuntu/ray/python/ray/rllib/es/es.py", line 19, in <module> from ray.rllib.es import policies File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 168, in __enter__ File "<frozen importlib._bootstrap>", line 110, in acquire _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('ray.rllib.es.policies') at 139937598221224
17,761
ray-project/ray
ray-project__ray-3238
60b22d9a722984e231db9d56b88512b30bdc0bd3
diff --git a/python/ray/tune/ray_trial_executor.py b/python/ray/tune/ray_trial_executor.py --- a/python/ray/tune/ray_trial_executor.py +++ b/python/ray/tune/ray_trial_executor.py @@ -278,6 +278,7 @@ def on_step_begin(self): def save(self, trial, storage=Checkpoint.DISK): """Saves the trial's state to a checkpoint.""" trial._checkpoint.storage = storage + trial._checkpoint.last_result = trial.last_result if storage == Checkpoint.MEMORY: trial._checkpoint.value = trial.runner.save_to_object.remote() else: @@ -301,6 +302,8 @@ def restore(self, trial, checkpoint=None): ray.get(trial.runner.restore_from_object.remote(value)) else: ray.get(trial.runner.restore.remote(value)) + trial.last_result = checkpoint.last_result + return True except Exception: logger.exception("Error restoring runner.") diff --git a/python/ray/tune/trial.py b/python/ray/tune/trial.py --- a/python/ray/tune/trial.py +++ b/python/ray/tune/trial.py @@ -85,9 +85,10 @@ class Checkpoint(object): MEMORY = "memory" DISK = "disk" - def __init__(self, storage, value): + def __init__(self, storage, value, last_result=None): self.storage = storage self.value = value + self.last_result = last_result @staticmethod def from_object(value=None): @@ -277,6 +278,14 @@ def _status_string(self): def has_checkpoint(self): return self._checkpoint.value is not None + def should_recover(self): + """Returns whether the trial qualifies for restoring. + + This is if a checkpoint frequency is set, which includes settings + where there may not yet be a checkpoint. + """ + return self.checkpoint_freq > 0 + def update_last_result(self, result, terminate=False): if terminate: result.update(done=True) diff --git a/python/ray/tune/trial_executor.py b/python/ray/tune/trial_executor.py --- a/python/ray/tune/trial_executor.py +++ b/python/ray/tune/trial_executor.py @@ -4,7 +4,6 @@ from __future__ import print_function import logging -import traceback from ray.tune.trial import Trial, Checkpoint @@ -61,24 +60,24 @@ def stop_trial(self, trial, error=False, error_msg=None, stop_logger=True): "stop_trial() method") def restart_trial(self, trial, error_msg=None): - """Restarts the trial. + """Restarts or requeues the trial. - The state of the trial should restore from the last checkpoint. + The state of the trial should restore from the last checkpoint. Trial + is requeued if the cluster no longer has resources to accomodate it. Args: error_msg (str): Optional error message. """ - try: - logger.info( - "Attempting to recover trial state from last checkpoint") - self.stop_trial( - trial, error=True, error_msg=error_msg, stop_logger=False) - trial.result_logger.flush() + self.stop_trial( + trial, + error=error_msg is not None, + error_msg=error_msg, + stop_logger=False) + trial.result_logger.flush() + if self.has_resources(trial.resources): self.start_trial(trial) - except Exception: - error_msg = traceback.format_exc() - logger.exception("Error recovering trial from checkpoint, abort.") - self.stop_trial(trial, error=True, error_msg=error_msg) + else: + trial.status = Trial.PENDING def continue_training(self, trial): """Continues the training of this trial.""" diff --git a/python/ray/tune/trial_runner.py b/python/ray/tune/trial_runner.py --- a/python/ray/tune/trial_runner.py +++ b/python/ray/tune/trial_runner.py @@ -297,7 +297,7 @@ def _process_events(self): logger.exception("Error processing event.") error_msg = traceback.format_exc() if trial.status == Trial.RUNNING: - if trial.has_checkpoint() and \ + if trial.should_recover() and \ trial.num_failures < trial.max_failures: self._try_recover(trial, error_msg) else:
[tune] Trial executor crashes on node removal in xray <!-- General questions should be asked on the mailing list ray-dev@googlegroups.com. Before submitting an issue, please fill out the following form. --> ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: - **Ray installed from (source or binary)**: binary - **Ray version**: 0.5.2 - **Python version**: 2.7 - **Exact command to reproduce**: ``` == Status == Using FIFO scheduling algorithm. Resources requested: 99/256 CPUs, 3/4 GPUs Result logdir: /home/ubuntu/ray_results/atari-impala ERROR trials: - IMPALA_BeamRiderNoFrameskip-v4_1_env=BeamRiderNoFrameskip-v4: ERROR, 1 failures: /home/ubuntu/ray_results/atari-impala/IMPALA_BeamRiderNoFrameskip-v4_1_env=BeamRiderNoFrameskip-v4_2018-09-09_23-41-15GCdo68/error_2018-09-09_23-44-49.txt [pid=26010], 193 s, 6 iter, 380750 ts, 401 rew RUNNING trials: - IMPALA_BreakoutNoFrameskip-v4_0_env=BreakoutNoFrameskip-v4: RUNNING [pid=26046], 193 s, 6 iter, 378750 ts, 8.15 rew - IMPALA_QbertNoFrameskip-v4_2_env=QbertNoFrameskip-v4: RUNNING [pid=26033], 194 s, 6 iter, 391250 ts, 300 rew - IMPALA_SpaceInvadersNoFrameskip-v4_3_env=SpaceInvadersNoFrameskip-v4: RUNNING [pid=26021], 193 s, 6 iter, 382500 ts, 212 rew A worker died or was killed while executing task 0000000030003bc01e1113c07967cbbfffa54f7a. A worker died or was killed while executing task 00000000278f319e0918aff7b8ba3c67ca7e4caf. A worker died or was killed while executing task 000000002b068851a815f7af6f532e7868697a94. A worker died or was killed while executing task 00000000602c103969d4f2cdea5a27759b576492. A worker died or was killed while executing task 00000000d5e61fdd4fbfd6f33eda7a7fe8b9f06e. A worker died or was killed while executing task 00000000a2c607f67fbfaf56a0868fa459895dfa. A worker died or was killed while executing task 0000000016390605fb225586db66c37f4d88c0b2. A worker died or was killed while executing task 00000000dae4eec56597b4790904c72ed6034529. Traceback (most recent call last): File "./train.py", line 118, in <module> A worker died or was killed while executing task 000000004c0abfa50e320361265b7d3446038b1b. run(args, parser) A worker died or was killed while executing task 00000000e7b81db3eef71ce561edfbfc14133466. File "./train.py", line 112, in run A worker died or was killed while executing task 00000000a83b970ac64b2b050e7988b5a9f98d54. A worker died or was killed while executing task 00000000f92be4b92ae8bfc43886ed97272fc1cc. queue_trials=args.queue_trials) File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/ray/tune/tune.py", line 102, in run_experiments A worker died or was killed while executing task 00000000fddb28c7a3346a66fd203c0e52e30c7e. runner.step() File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/ray/tune/trial_runner.py", line 101, in step A worker died or was killed while executing task 00000000edba4e591ebf8a89b35c26bec6d12474. self.trial_executor.on_step_begin() A worker died or was killed while executing task 00000000c3149efa851aea1b391fe181a7b3f419. File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/ray/tune/ray_trial_executor.py", line 252, in on_step_begin A worker died or was killed while executing task 00000000a2d156fc320d7557c8fa923d141caec7. self._update_avail_resources() File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/ray/tune/ray_trial_executor.py", line 197, in _update_avail_resources A worker died or was killed while executing task 000000004508d8f47c933f2aa81027b6660e8bf4. num_cpus = sum(cl['Resources']['CPU'] for cl in clients) File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/ray/tune/ray_trial_executor.py", line 197, in <genexpr> num_cpus = sum(cl['Resources']['CPU'] for cl in clients) KeyError: 'CPU' ```
@atumanov @robertnishihara To try to reproduce this, I started ray twice on the same node (once as head, once as worker to connect to head). I opened an interpreter to connect to ray, checking the client table: ```python In [4]: ray.global_state.client_table() Out[4]: [{'ClientID': 'e619bc437872c4ec9fa34b963bb3cf10e23b48f4', 'IsInsertion': True, 'NodeManagerAddress': '169.229.49.173', 'NodeManagerPort': 40347, 'ObjectManagerPort': 43791, 'ObjectStoreSocketName': '/tmp/plasma_store82307007', 'RayletSocketName': '/tmp/raylet27088953', 'Resources': {'GPU': 1.0, 'CPU': 4.0}}, {'ClientID': '2d596eab937a8cced74b72d904c1da578cdb7cdb', 'IsInsertion': True, 'NodeManagerAddress': '169.229.49.173', 'NodeManagerPort': 46637, 'ObjectManagerPort': 38235, 'ObjectStoreSocketName': '/tmp/plasma_store53490427', 'RayletSocketName': '/tmp/raylet23718122', 'Resources': {'GPU': 1.0, 'CPU': 4.0}}] ``` I then killed the second raylet, which gave me this message: ```python In [5]: The node with client ID 2d596eab937a8cced74b72d904c1da578cdb7cdb has been marked dead because the monitor has missed too many heartbeats from it. ``` But I checked the client table and now I have 3 entries. *Is this intended? Note that the 2nd and 3rd entry have the same client ID.* ```python In [7]: ray.global_state.client_table() Out[7]: [{'ClientID': 'e619bc437872c4ec9fa34b963bb3cf10e23b48f4', 'IsInsertion': True, 'NodeManagerAddress': '169.229.49.173', 'NodeManagerPort': 40347, 'ObjectManagerPort': 43791, 'ObjectStoreSocketName': '/tmp/plasma_store82307007', 'RayletSocketName': '/tmp/raylet27088953', 'Resources': {'GPU': 1.0, 'CPU': 4.0}}, {'ClientID': '2d596eab937a8cced74b72d904c1da578cdb7cdb', 'IsInsertion': True, 'NodeManagerAddress': '169.229.49.173', 'NodeManagerPort': 46637, 'ObjectManagerPort': 38235, 'ObjectStoreSocketName': '/tmp/plasma_store53490427', 'RayletSocketName': '/tmp/raylet23718122', 'Resources': {'GPU': 1.0, 'CPU': 4.0}}, {'ClientID': '2d596eab937a8cced74b72d904c1da578cdb7cdb', 'IsInsertion': False, 'NodeManagerAddress': '', 'NodeManagerPort': 0, 'ObjectManagerPort': 0, 'ObjectStoreSocketName': '', 'RayletSocketName': '', 'Resources': {}}] ``` @richardliaw That's how it currently works (but this is confusing and should probably be changed). In Xray, the client table is stored in the GCS as an append-only log, so node deletion is achieved simply by appending another entry with `IsInsertion = False`. However, this should probably not be exposed to the user. We could switch to https://github.com/ray-project/ray/pull/2501 once that's merged. @pschafhalter does https://github.com/ray-project/ray/pull/2501/files work correctly in this case above? I looked at the code briefly and didn't see any handling of `IsInsertion`. @pschafhalter Looks like it doesn't work (#2875). After #2582 is closed, we can change this part of the code to be `.get(resource, 0)`.
2018-11-05T08:05:22Z
[]
[]
Traceback (most recent call last): File "./train.py", line 118, in <module> A worker died or was killed while executing task 000000004c0abfa50e320361265b7d3446038b1b.
17,785
ray-project/ray
ray-project__ray-3293
d681893b0f196f6599433a4c59d9edb5d858eabb
diff --git a/python/ray/tune/trainable.py b/python/ray/tune/trainable.py --- a/python/ray/tune/trainable.py +++ b/python/ray/tune/trainable.py @@ -161,14 +161,14 @@ def train(self): result.setdefault(DONE, False) # self._timesteps_total should only be tracked if increments provided - if result.get(TIMESTEPS_THIS_ITER): + if result.get(TIMESTEPS_THIS_ITER) is not None: if self._timesteps_total is None: self._timesteps_total = 0 self._timesteps_total += result[TIMESTEPS_THIS_ITER] self._timesteps_since_restore += result[TIMESTEPS_THIS_ITER] - # self._timesteps_total should only be tracked if increments provided - if result.get(EPISODES_THIS_ITER): + # self._episodes_total should only be tracked if increments provided + if result.get(EPISODES_THIS_ITER) is not None: if self._episodes_total is None: self._episodes_total = 0 self._episodes_total += result[EPISODES_THIS_ITER]
[tune] Trial executor crashes with certain stop conditions <!-- General questions should be asked on the mailing list ray-dev@googlegroups.com. Before submitting an issue, please fill out the following form. --> ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: - **Ray installed from (source or binary)**: - **Ray version**: - **Python version**: - **Exact command to reproduce**: <!-- You can obtain the Ray version with python -c "import ray; print(ray.__version__)" --> ### Describe the problem It seems one trial finishes, but the rest fail. ### Source code / logs ``` Traceback (most recent call last): File "/home/eric/Desktop/ray-private/python/ray/tune/trial_runner.py", line 242, in _process_events if trial.should_stop(result): File "/home/eric/Desktop/ray-private/python/ray/tune/trial.py", line 213, in should_stop if result[criteria] >= stop_value: TypeError: unorderable types: NoneType() >= int() Worker ip unknown, skipping log sync for /home/eric/ray_results/test/IMPALA_cartpole_stateless_4_2018-10-14_00-11-54wk3lun7w == Status == Using FIFO scheduling algorithm. Resources requested: 0/4 CPUs, 0/0 GPUs Result logdir: /home/eric/ray_results/test ERROR trials: - IMPALA_cartpole_stateless_1: ERROR, 1 failures: /home/eric/ray_results/test/IMPALA_cartpole_stateless_1_2018-10-14_00-11-08bzsn9bjz/error_2018-10-14_00-11-23.txt - IMPALA_cartpole_stateless_2: ERROR, 1 failures: /home/eric/ray_results/test/IMPALA_cartpole_stateless_2_2018-10-14_00-11-23zv6jbrbr/error_2018-10-14_00-11-38.txt - IMPALA_cartpole_stateless_3: ERROR, 1 failures: /home/eric/ray_results/test/IMPALA_cartpole_stateless_3_2018-10-14_00-11-38p18gjmul/error_2018-10-14_00-11-54.txt - IMPALA_cartpole_stateless_4: ERROR, 1 failures: /home/eric/ray_results/test/IMPALA_cartpole_stateless_4_2018-10-14_00-11-54wk3lun7w/error_2018-10-14_00-12-09.txt TERMINATED trials: - IMPALA_cartpole_stateless_0: TERMINATED [pid=19362], 173 s, 17 iter, 143900 ts, 221 rew ``` ``` tune.run_experiments({ "test": { "env": "cartpole_stateless", "run": "IMPALA", "num_samples": 5, "stop": { "episode_reward_mean": args.stop, "timesteps_total": 200000, }, "config": { "num_workers": 2, "num_gpus": 0, "vf_loss_coeff": 0.01, "model": { "use_lstm": True, }, }, } }) ```
@richardliaw
2018-11-10T23:13:39Z
[]
[]
Traceback (most recent call last): File "/home/eric/Desktop/ray-private/python/ray/tune/trial_runner.py", line 242, in _process_events if trial.should_stop(result): File "/home/eric/Desktop/ray-private/python/ray/tune/trial.py", line 213, in should_stop if result[criteria] >= stop_value: TypeError: unorderable types: NoneType() >= int()
17,788
ray-project/ray
ray-project__ray-3621
ddd4c842f1eb34097cc3f8795c823fd044a56fc4
diff --git a/python/ray/__init__.py b/python/ray/__init__.py --- a/python/ray/__init__.py +++ b/python/ray/__init__.py @@ -47,7 +47,7 @@ raise modin_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "modin") -sys.path.insert(0, modin_path) +sys.path.append(modin_path) from ray.raylet import ObjectID, _config # noqa: E402 from ray.profiling import profile # noqa: E402
[modin] Importing Modin before Ray can sometimes cause ImportError ### Describe the problem <!-- Describe the problem clearly here. --> When running Modin with Ray installed from source, I am sometimes running into `ImportError` and `ModuleNotFoundError` which is occurring when I am running a modified version of Modin. This forces me to modify Ray's source such that it does not try to use the Modin that is bundled with Ray. I will work on a solution for this. ### Source code / logs `import modin.pandas as pd` ``` Traceback (most recent call last): File "/home/ubuntu/ray/python/ray/function_manager.py", line 165, in fetch_and_register_remote_function function = pickle.loads(serialized_function) ModuleNotFoundError: No module named 'modin.data_management.utils' ```
Is that exception raised on a worker or the driver? It is raised in every worker immediately after import.
2018-12-23T18:46:25Z
[]
[]
Traceback (most recent call last): File "/home/ubuntu/ray/python/ray/function_manager.py", line 165, in fetch_and_register_remote_function function = pickle.loads(serialized_function) ModuleNotFoundError: No module named 'modin.data_management.utils'
17,801
ray-project/ray
ray-project__ray-3711
e78562b2e8d2affc8b0f7fabde37aa192b4385fc
diff --git a/python/ray/tune/registry.py b/python/ray/tune/registry.py --- a/python/ray/tune/registry.py +++ b/python/ray/tune/registry.py @@ -2,6 +2,7 @@ from __future__ import division from __future__ import print_function +import logging from types import FunctionType import ray @@ -17,6 +18,8 @@ TRAINABLE_CLASS, ENV_CREATOR, RLLIB_MODEL, RLLIB_PREPROCESSOR ] +logger = logging.getLogger(__name__) + def register_trainable(name, trainable): """Register a trainable function or class. @@ -30,8 +33,16 @@ def register_trainable(name, trainable): from ray.tune.trainable import Trainable, wrap_function - if isinstance(trainable, FunctionType): + if isinstance(trainable, type): + logger.debug("Detected class for trainable.") + elif isinstance(trainable, FunctionType): + logger.debug("Detected function for trainable.") + trainable = wrap_function(trainable) + elif callable(trainable): + logger.warning( + "Detected unknown callable for trainable. Converting to class.") trainable = wrap_function(trainable) + if not issubclass(trainable, Trainable): raise TypeError("Second argument must be convertable to Trainable", trainable)
[tune[ partial function cannot be registered as trainable ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: Ubuntu 18.04 - **Ray installed from (source or binary)**: binary - **Ray version**: 0.6.1 - **Python version**: 3.7 - **Exact command to reproduce**: The following code fails: ``` def dummy_fn(c, a, b): print("Called") from functools import partial from ray.tune import register_trainable register_trainable("test", partial(dummy_fn, c=None)) ``` while the following code works: ``` def dummy_fn(a, b): print("Called") from functools import partial from ray.tune import register_trainable register_trainable("test", dummy_fn) ``` ### Describe the problem The first code sample does not work, despite the function (after the `partial`) fullfills all requirements to be properly registered. ### Source code / logs Traceback: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/temp/schock/conda/envs/delira_new/lib/python3.7/site-packages/ray/tune/registry.py", line 35, in register_trainable if not issubclass(trainable, Trainable): TypeError: issubclass() arg 1 must be a class ```
2019-01-07T20:01:03Z
[]
[]
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/temp/schock/conda/envs/delira_new/lib/python3.7/site-packages/ray/tune/registry.py", line 35, in register_trainable if not issubclass(trainable, Trainable): TypeError: issubclass() arg 1 must be a class
17,808
ray-project/ray
ray-project__ray-3793
75ac016e2bd39060d14a302292546d9dbc49f6a2
diff --git a/python/ray/actor.py b/python/ray/actor.py --- a/python/ray/actor.py +++ b/python/ray/actor.py @@ -779,6 +779,13 @@ def __setstate__(self, state): def make_actor(cls, num_cpus, num_gpus, resources, actor_method_cpus, checkpoint_interval, max_reconstructions): + # Give an error if cls is an old-style class. + if not issubclass(cls, object): + raise TypeError( + "The @ray.remote decorator cannot be applied to old-style " + "classes. In Python 2, you must declare the class with " + "'class ClassName(object):' instead of 'class ClassName:'.") + if checkpoint_interval is None: checkpoint_interval = -1 if max_reconstructions is None:
Actor definition needs Actor(object). The following code does not work on Python 2 but works on Python 3. ``` import ray ray.init() @ray.remote class Outer(): def __init__(self): pass ``` Error thrown: ``` Traceback (most recent call last): File "/Users/rliaw/miniconda2/envs/py2/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/Users/rliaw/miniconda2/envs/py2/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "/Users/rliaw/miniconda2/envs/py2/lib/python2.7/site-packages/ray/worker.py", line 1166, in import_thread worker.fetch_and_register_actor(key, worker) File "/Users/rliaw/miniconda2/envs/py2/lib/python2.7/site-packages/ray/actor.py", line 86, in fetch_and_register_actor worker.actors[actor_id_str] = unpickled_class.__new__(unpickled_class) AttributeError: class Class has no attribute '__new__' ```
Do we want to support old-style classes? We should certainly give a better error message. Better error message: Yes! It's ok to not support old-style classes for actors I think. I tagged it with "help wanted" as it looks like a low hanging fruit that would be perfect for somebody to look into to contribute to the project.
2019-01-16T23:47:15Z
[]
[]
Traceback (most recent call last): File "/Users/rliaw/miniconda2/envs/py2/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/Users/rliaw/miniconda2/envs/py2/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "/Users/rliaw/miniconda2/envs/py2/lib/python2.7/site-packages/ray/worker.py", line 1166, in import_thread worker.fetch_and_register_actor(key, worker) File "/Users/rliaw/miniconda2/envs/py2/lib/python2.7/site-packages/ray/actor.py", line 86, in fetch_and_register_actor worker.actors[actor_id_str] = unpickled_class.__new__(unpickled_class) AttributeError: class Class has no attribute '__new__'
17,811
ray-project/ray
ray-project__ray-4237
348328225489ab18041e4a10152af5adda9366b0
diff --git a/python/ray/tune/trial.py b/python/ray/tune/trial.py --- a/python/ray/tune/trial.py +++ b/python/ray/tune/trial.py @@ -299,6 +299,24 @@ def __init__(self, self.error_file = None self.num_failures = 0 + # AutoML fields + self.results = None + self.best_result = None + self.param_config = None + self.extra_arg = None + + self._nonjson_fields = [ + "_checkpoint", + "config", + "loggers", + "sync_function", + "last_result", + "results", + "best_result", + "param_config", + "extra_arg", + ] + self.trial_name = None if trial_name_creator: self.trial_name = trial_name_creator(self) @@ -509,17 +527,8 @@ def __getstate__(self): state = self.__dict__.copy() state["resources"] = resources_to_json(self.resources) - # These are non-pickleable entries. - pickle_data = { - "_checkpoint": self._checkpoint, - "config": self.config, - "loggers": self.loggers, - "sync_function": self.sync_function, - "last_result": self.last_result - } - - for key, value in pickle_data.items(): - state[key] = binary_to_hex(cloudpickle.dumps(value)) + for key in self._nonjson_fields: + state[key] = binary_to_hex(cloudpickle.dumps(state.get(key))) state["runner"] = None state["result_logger"] = None @@ -535,10 +544,7 @@ def __getstate__(self): def __setstate__(self, state): logger_started = state.pop("__logger_started__") state["resources"] = json_to_resources(state["resources"]) - for key in [ - "_checkpoint", "config", "loggers", "sync_function", - "last_result" - ]: + for key in self._nonjson_fields: state[key] = cloudpickle.loads(hex_to_binary(state[key])) self.__dict__.update(state)
[tune] genetic_example.py --smoke-test output should be reduced ``` 2019-03-03 10:58:40,611 INFO genetic_searcher.py:68 -- [GENETIC SEARCH] Generate the 1th generation, population=10 2019-03-03 10:58:40,678 INFO search_policy.py:115 -- =========== BEGIN Experiment-Round: 1 [10 NEW | 10 TOTAL] =========== 2019-03-03 10:58:41,430 ERROR trial_runner.py:252 -- Trial Runner checkpointing failed. Traceback (most recent call last): File "/ray/python/ray/tune/trial_runner.py", line 250, in step self.checkpoint() File "/ray/python/ray/tune/trial_runner.py", line 144, in checkpoint json.dump(runner_state, f, indent=2) File "/opt/conda/lib/python2.7/json/__init__.py", line 189, in dump for chunk in iterable: File "/opt/conda/lib/python2.7/json/encoder.py", line 434, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "/opt/conda/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict for chunk in chunks: File "/opt/conda/lib/python2.7/json/encoder.py", line 332, in _iterencode_list for chunk in chunks: File "/opt/conda/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict for chunk in chunks: File "/opt/conda/lib/python2.7/json/encoder.py", line 332, in _iterencode_list for chunk in chunks: File "/opt/conda/lib/python2.7/json/encoder.py", line 442, in _iterencode o = _default(o) File "/opt/conda/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) is not JSON serializable 2019-03-03 10:58:41,449 ERROR trial_runner.py:252 -- Trial Runner checkpointing failed. ```
2019-03-03T22:19:31Z
[]
[]
Traceback (most recent call last): File "/ray/python/ray/tune/trial_runner.py", line 250, in step self.checkpoint() File "/ray/python/ray/tune/trial_runner.py", line 144, in checkpoint json.dump(runner_state, f, indent=2) File "/opt/conda/lib/python2.7/json/__init__.py", line 189, in dump for chunk in iterable: File "/opt/conda/lib/python2.7/json/encoder.py", line 434, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File "/opt/conda/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict for chunk in chunks: File "/opt/conda/lib/python2.7/json/encoder.py", line 332, in _iterencode_list for chunk in chunks: File "/opt/conda/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict for chunk in chunks: File "/opt/conda/lib/python2.7/json/encoder.py", line 332, in _iterencode_list for chunk in chunks: File "/opt/conda/lib/python2.7/json/encoder.py", line 442, in _iterencode o = _default(o) File "/opt/conda/lib/python2.7/json/encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
17,824
ray-project/ray
ray-project__ray-4504
ab55a1f93a15e7b6bbfac0805e362505a9fbcf88
diff --git a/python/ray/rllib/agents/dqn/dqn_policy_graph.py b/python/ray/rllib/agents/dqn/dqn_policy_graph.py --- a/python/ray/rllib/agents/dqn/dqn_policy_graph.py +++ b/python/ray/rllib/agents/dqn/dqn_policy_graph.py @@ -387,9 +387,9 @@ def __init__(self, observation_space, action_space, config): # update_target_fn will be called periodically to copy Q network to # target Q network update_target_expr = [] - for var, var_target in zip( - sorted(self.q_func_vars, key=lambda v: v.name), - sorted(self.target_q_func_vars, key=lambda v: v.name)): + assert len(self.q_func_vars) == len(self.target_q_func_vars), \ + (self.q_func_vars, self.target_q_func_vars) + for var, var_target in zip(self.q_func_vars, self.target_q_func_vars): update_target_expr.append(var_target.assign(var)) self.update_target_expr = tf.group(*update_target_expr)
Inconsistent weight assignment operations in DQNPolicyGraph <!-- General questions should be asked on the mailing list ray-dev@googlegroups.com. Questions about how to use Ray should be asked on [StackOverflow](https://stackoverflow.com/questions/tagged/ray). Before submitting an issue, please fill out the following form. --> ### System information - **OS Platform and Distribution (e.g., macOS 10.14.3)**: - **Ray installed from (source or binary)**: source - **Ray version**: 0.7.0.dev2 ab55a1f9 - **Python version**: 3.6.8 <!-- You can obtain the Ray version with python -c "import ray; print(ray.__version__)" --> ### Describe the problem <!-- Describe the problem clearly here. --> `DQNPolicyGraph` creates tensorflow assign operations by looping through lists of `self.q_func_vars` and `self.target_q_func_vars` sorted by variable name on lines 390:393. The default sorting is not consistent between the two lists of variable names and as a result the operations can mix up the assignments. The attached code snippet produces the error message below. ``` 2019-03-28 18:34:31,402 WARNING worker.py:1397 -- WARNING: Not updating worker name since `setproctitle` is not installed. Install this with `pip install setproctitle` (or ray[debug]) to enable monitoring of worker processes. 2019-03-28 18:34:31.415440: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA WARNING:tensorflow:From /Users/ristovuorio/miniconda3/envs/ray_fiddle/lib/python3.6/site-packages/tensorflow/python/util/decorator_utils.py:127: GraphKeys.VARIABLES (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Use `tf.GraphKeys.GLOBAL_VARIABLES` instead. Traceback (most recent call last): File "dqn_fail_demonstrator.py", line 37, in <module> trainer = DQNAgent(env="CartPole-v0", config=config) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/agent.py", line 280, in __init__ Trainable.__init__(self, config, logger_creator) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/tune/trainable.py", line 88, in __init__ self._setup(copy.deepcopy(self.config)) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/agent.py", line 377, in _setup self._init() File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/dqn/dqn.py", line 207, in _init self.env_creator, self._policy_graph) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/agent.py", line 510, in make_local_evaluator extra_config or {})) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/agent.py", line 727, in _make_evaluator async_remote_worker_envs=config["async_remote_worker_envs"]) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/evaluation/policy_evaluator.py", line 296, in __init__ self._build_policy_map(policy_dict, policy_config) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/evaluation/policy_evaluator.py", line 692, in _build_policy_map policy_map[name] = cls(obs_space, act_space, merged_conf) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/dqn/dqn_policy_graph.py", line 394, in __init__ update_target_expr.append(var_target.assign(var)) File "/Users/ristovuorio/miniconda3/envs/ray_fiddle/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 951, in assign self._shape.assert_is_compatible_with(value_tensor.shape) File "/Users/ristovuorio/miniconda3/envs/ray_fiddle/lib/python3.6/site-packages/tensorflow/python/framework/tensor_shape.py", line 848, in assert_is_compatible_with raise ValueError("Shapes %s and %s are incompatible" % (self, other)) ValueError: Shapes (3,) and (11,) are incompatible ``` ### Source code / logs <!-- Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached. Try to provide a reproducible test case that is the bare minimum necessary to generate the problem. --> ``` from tensorflow.keras.layers import Dense import ray from ray.rllib.models import ModelCatalog, Model from ray.rllib.agents.dqn import DQNAgent class DemoNN(Model): def _build_layers_v2(self, input_dict, num_outputs, options): x = input_dict["obs"] x = Dense(1)(x) x = Dense(1)(x) x = Dense(3)(x) x = Dense(1)(x) x = Dense(1)(x) x = Dense(1)(x) x = Dense(1)(x) x = Dense(1)(x) x = Dense(1)(x) x = Dense(1)(x) x = Dense(11)(x) x = Dense(2)(x) return x, x ray.init(local_mode=True) ModelCatalog.register_custom_model("demo_nn", DemoNN) config = { "model": { "custom_model": "demo_nn", }, "hiddens": [], "num_workers": 0, } trainer = DQNAgent(env="CartPole-v0", config=config) ```
Would removing the sorted() be the right fix here? According to the TF docs for get_collection(), the variables are already returned in the "order they were collected", which is presumably a consistent order. Yup, that seems to fix it.
2019-03-28T23:48:48Z
[]
[]
Traceback (most recent call last): File "dqn_fail_demonstrator.py", line 37, in <module> trainer = DQNAgent(env="CartPole-v0", config=config) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/agent.py", line 280, in __init__ Trainable.__init__(self, config, logger_creator) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/tune/trainable.py", line 88, in __init__ self._setup(copy.deepcopy(self.config)) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/agent.py", line 377, in _setup self._init() File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/dqn/dqn.py", line 207, in _init self.env_creator, self._policy_graph) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/agent.py", line 510, in make_local_evaluator extra_config or {})) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/agent.py", line 727, in _make_evaluator async_remote_worker_envs=config["async_remote_worker_envs"]) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/evaluation/policy_evaluator.py", line 296, in __init__ self._build_policy_map(policy_dict, policy_config) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/evaluation/policy_evaluator.py", line 692, in _build_policy_map policy_map[name] = cls(obs_space, act_space, merged_conf) File "/Users/ristovuorio/projects/ray_doodle/ray/python/ray/rllib/agents/dqn/dqn_policy_graph.py", line 394, in __init__ update_target_expr.append(var_target.assign(var)) File "/Users/ristovuorio/miniconda3/envs/ray_fiddle/lib/python3.6/site-packages/tensorflow/python/ops/resource_variable_ops.py", line 951, in assign self._shape.assert_is_compatible_with(value_tensor.shape) File "/Users/ristovuorio/miniconda3/envs/ray_fiddle/lib/python3.6/site-packages/tensorflow/python/framework/tensor_shape.py", line 848, in assert_is_compatible_with raise ValueError("Shapes %s and %s are incompatible" % (self, other)) ValueError: Shapes (3,) and (11,) are incompatible
17,834
ray-project/ray
ray-project__ray-5002
7bda5edc16d40880b16ac04a5421dbfe79f4ccb2
diff --git a/python/ray/experimental/signal.py b/python/ray/experimental/signal.py --- a/python/ray/experimental/signal.py +++ b/python/ray/experimental/signal.py @@ -2,6 +2,8 @@ from __future__ import division from __future__ import print_function +import logging + from collections import defaultdict import ray @@ -13,6 +15,8 @@ # in node_manager.cc ACTOR_DIED_STR = "ACTOR_DIED_SIGNAL" +logger = logging.getLogger(__name__) + class Signal(object): """Base class for Ray signals.""" @@ -125,10 +129,16 @@ def receive(sources, timeout=None): for s in sources: task_id_to_sources[_get_task_id(s).hex()].append(s) + if timeout < 1e-3: + logger.warning("Timeout too small. Using 1ms minimum") + timeout = 1e-3 + + timeout_ms = int(1000 * timeout) + # Construct the redis query. query = "XREAD BLOCK " - # Multiply by 1000x since timeout is in sec and redis expects ms. - query += str(1000 * timeout) + # redis expects ms. + query += str(timeout_ms) query += " STREAMS " query += " ".join([task_id for task_id in task_id_to_sources]) query += " "
Non-integer timeout for signal.receive causes malformed redis query <!-- General questions should be asked on the mailing list ray-dev@googlegroups.com. Questions about how to use Ray should be asked on [StackOverflow](https://stackoverflow.com/questions/tagged/ray). Before submitting an issue, please fill out the following form. --> ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: Ubuntu 18.04 - **Ray installed from (source or binary)**: source - **Ray version**: 0.7.0.dev2 - **Python version**: 3.7.2 ### Describe the problem The timeout argument in `signal.receive()` does not work with non-integer values. For instance, calling `signal.receive(sources, timeout=0.01)` causes a `redis.exceptions.ResponseError: timeout is not an integer or out of range`. This is because of L131 in `signal.py`, where the timeout is converted to ms and then converted to a string - redis expects an int, but if you pass a double to the method (like 0.1), the result of `str(1000 * timeout)` is `100.0`. The correct string would have been `100`. A fix would be to change `str(1000 * timeout)` to `str(int(1000 * timeout))` and have checks to ensure timeout is not < 1000. https://github.com/ray-project/ray/blob/d951eb740ffe22c385d75df62aa18da790706804/python/ray/experimental/signal.py#L129-L133 ### Source code / logs Traceback: ``` Traceback (most recent call last): File "driver.py", line 21, in <module> signals = signal.receive(self.clients, timeout=0.01) File "/home/romilb/ray/python/ray/experimental/signal.py", line 141, in receive answers = ray.worker.global_worker.redis_client.execute_command(query) File "/home/romilb/anaconda3/lib/python3.7/site-packages/redis/client.py", line 668, in execute_command return self.parse_response(connection, command_name, **options) File "/home/romilb/anaconda3/lib/python3.7/site-packages/redis/client.py", line 680, in parse_response response = connection.read_response() File "/home/romilb/anaconda3/lib/python3.7/site-packages/redis/connection.py", line 629, in read_response raise response redis.exceptions.ResponseError: timeout is not an integer or out of range ``` I also printed the corresponding redis query: ``` (pid=31330) XREAD BLOCK 10.0 STREAMS fc96f993802bb5a31b5868e69179fe76b62b7c3b 0 ```
I'm experiencing this problem. Seems like an easy fix, is this all that needs to happen? Yes, do you want to submit a PR? I do On Wed, Jun 19, 2019, 4:06 PM Philipp Moritz <notifications@github.com> wrote: > Yes, do you want to submit a PR? > > — > You are receiving this because you commented. > Reply to this email directly, view it on GitHub > <https://github.com/ray-project/ray/issues/4674?email_source=notifications&email_token=ACDIN2RSR35IO4D3K6MZI7DP3KGVLA5CNFSM4HHJEO32YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODYDEFXA#issuecomment-503726812>, > or mute the thread > <https://github.com/notifications/unsubscribe-auth/ACDIN2RVVWSIZC622HFFQTLP3KGVLANCNFSM4HHJEO3Q> > . >
2019-06-19T20:44:09Z
[]
[]
Traceback (most recent call last): File "driver.py", line 21, in <module> signals = signal.receive(self.clients, timeout=0.01) File "/home/romilb/ray/python/ray/experimental/signal.py", line 141, in receive answers = ray.worker.global_worker.redis_client.execute_command(query) File "/home/romilb/anaconda3/lib/python3.7/site-packages/redis/client.py", line 668, in execute_command return self.parse_response(connection, command_name, **options) File "/home/romilb/anaconda3/lib/python3.7/site-packages/redis/client.py", line 680, in parse_response response = connection.read_response() File "/home/romilb/anaconda3/lib/python3.7/site-packages/redis/connection.py", line 629, in read_response raise response redis.exceptions.ResponseError: timeout is not an integer or out of range
17,850
ray-project/ray
ray-project__ray-5097
1cf7728f359bd26bc54a52ded3373b8c8a37311b
diff --git a/python/ray/tune/schedulers/pbt.py b/python/ray/tune/schedulers/pbt.py --- a/python/ray/tune/schedulers/pbt.py +++ b/python/ray/tune/schedulers/pbt.py @@ -268,8 +268,8 @@ def _log_config_on_step(self, trial_state, new_state, trial, "pbt_policy_" + trial_to_clone_id + ".txt") policy = [ trial_name, trial_to_clone_name, - trial.last_result[TRAINING_ITERATION], - trial_to_clone.last_result[TRAINING_ITERATION], + trial.last_result.get(TRAINING_ITERATION, 0), + trial_to_clone.last_result.get(TRAINING_ITERATION, 0), trial_to_clone.config, new_config ] # Log to global file.
[tune] PBT perturbing after first iteration KeyError <!-- General questions should be asked on the mailing list ray-dev@googlegroups.com. Questions about how to use Ray should be asked on [StackOverflow](https://stackoverflow.com/questions/tagged/ray). Before submitting an issue, please fill out the following form. --> ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: Linux - **Ray installed from (source or binary)**: binary - **Ray version**: 0.7.1 - **Python version**: 3.7.3 - **Exact command to reproduce**: run PBT with `perturbation_interval=1` and `time_attr="training_iteration"`. ### Describe the problem Occasionally, with the above described config PBT attempts to perturb config before `trial.last_result` is populated. This results in `KeyError` and the worker dies. ### Source code / logs ```python Traceback (most recent call last): File "/home/magnus/.cache/pypoetry/virtualenvs/document-classification-py3.7/lib/python3.7/site-packages/ray/tune/trial_runner.py", line 458, in _process_trial self, trial, result) File "/home/magnus/.cache/pypoetry/virtualenvs/document-classification-py3.7/lib/python3.7/site-packages/ray/tune/schedulers/pbt.py", line 217, in on_trial_result self._exploit(trial_runner.trial_executor, trial, trial_to_clone) File "/home/magnus/.cache/pypoetry/virtualenvs/document-classification-py3.7/lib/python3.7/site-packages/ray/tune/schedulers/pbt.py", line 279, in _exploit trial_to_clone, new_config) File "/home/magnus/.cache/pypoetry/virtualenvs/document-classification-py3.7/lib/python3.7/site-packages/ray/tune/schedulers/pbt.py", line 244, in _log_config_on_step trial.last_result[TRAINING_ITERATION], KeyError: 'training_iteration' ```
Can you post what your `run` command looks like? (not actual code we're running, since it's scattered all over modules, but something like this) ```python experiment = ray.tune.Experiment( name=experiment_name, run=SupervisedTrainable, resources_per_trial={"cpu": cpu_fraction, "gpu": gpu_fraction}, stop=experiment_config.training.stopping_criteria, num_samples=4, config=resolved_config, checkpoint_at_end=True, checkpoint_freq=experiment_config.training.checkpoint_freq, ) scheduler = PopulationBasedTraining( time_attr="training_iteration", reward_attr="val/accuracy", perturbation_interval=1, hyperparam_mutations=hparam_mutations, ) ray.tune.run( experiment, scheduler=scheduler, reuse_actors=False ) ``` OK, I see what the issue is; I'll open a PR to fix.
2019-07-02T20:41:06Z
[]
[]
Traceback (most recent call last): File "/home/magnus/.cache/pypoetry/virtualenvs/document-classification-py3.7/lib/python3.7/site-packages/ray/tune/trial_runner.py", line 458, in _process_trial self, trial, result) File "/home/magnus/.cache/pypoetry/virtualenvs/document-classification-py3.7/lib/python3.7/site-packages/ray/tune/schedulers/pbt.py", line 217, in on_trial_result self._exploit(trial_runner.trial_executor, trial, trial_to_clone) File "/home/magnus/.cache/pypoetry/virtualenvs/document-classification-py3.7/lib/python3.7/site-packages/ray/tune/schedulers/pbt.py", line 279, in _exploit trial_to_clone, new_config) File "/home/magnus/.cache/pypoetry/virtualenvs/document-classification-py3.7/lib/python3.7/site-packages/ray/tune/schedulers/pbt.py", line 244, in _log_config_on_step trial.last_result[TRAINING_ITERATION], KeyError: 'training_iteration'
17,854
ray-project/ray
ray-project__ray-5208
4fa2a6006c305694a682086b1b52608cc3b7b8ee
diff --git a/python/ray/rllib/utils/debug.py b/python/ray/rllib/utils/debug.py --- a/python/ray/rllib/utils/debug.py +++ b/python/ray/rllib/utils/debug.py @@ -78,7 +78,10 @@ def _summarize(obj): elif isinstance(obj, tuple): return tuple(_summarize(x) for x in obj) elif isinstance(obj, np.ndarray): - if obj.dtype == np.object: + if obj.size == 0: + return _StringValue("np.ndarray({}, dtype={})".format( + obj.shape, obj.dtype)) + elif obj.dtype == np.object: return _StringValue("np.ndarray({}, dtype={}, head={})".format( obj.shape, obj.dtype, _summarize(obj[0]))) else: diff --git a/python/ray/rllib/utils/memory.py b/python/ray/rllib/utils/memory.py --- a/python/ray/rllib/utils/memory.py +++ b/python/ray/rllib/utils/memory.py @@ -56,7 +56,11 @@ def aligned_array(size, dtype, align=64): empty = np.empty(n + (align - 1), dtype=np.uint8) data_align = empty.ctypes.data % align offset = 0 if data_align == 0 else (align - data_align) - output = empty[offset:offset + n].view(dtype) + if n == 0: + # stop np from optimising out empty slice reference + output = empty[offset:offset + 1][0:0].view(dtype) + else: + output = empty[offset:offset + n].view(dtype) assert len(output) == size, len(output) assert output.ctypes.data % align == 0, output.ctypes.data
[rllib] utils.debug.summarize() dies on empty arrays # System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: Ubuntu 18.04 - **Ray installed from (source or binary)**: binary (pypi) - **Ray version**: 0.7.1 & 0.7.2 - **Python version**: 3.6 - **Exact command to reproduce**: N/A ### Describe the problem I'm running rllib on an environment that returns weird zero-length observations. RLLib chokes when it tries to summarise them because the arrays don't have a min/max/mean. Example traceback below. ### Source code / logs ``` 2019-07-16 14:10:09,054 ERROR trial_runner.py:487 -- Error processing event. Traceback (most recent call last): File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/tune/trial_runner.py", line 436, in _process_trial result = self.trial_executor.fetch_result(trial) …snip… File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/rllib/evaluation/sampler.py", line 308, in _env_runner summarize(unfiltered_obs))) File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/rllib/utils/debug.py", line 65, in summarize return _printer.pformat(_summarize(obj)) File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/rllib/utils/debug.py", line 70, in _summarize return {k: _summarize(v) for k, v in obj.items()} …snip… File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/rllib/utils/debug.py", line 87, in _summarize obj.shape, obj.dtype, round(float(np.min(obj)), 3), File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 2618, in amin initial=initial) File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 86, in _wrapreduction return ufunc.reduce(obj, axis, dtype, out, **passkwargs) ValueError: zero-size array to reduction operation minimum which has no identity ```
2019-07-16T21:36:58Z
[]
[]
Traceback (most recent call last): File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/tune/trial_runner.py", line 436, in _process_trial result = self.trial_executor.fetch_result(trial) …snip… File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/rllib/evaluation/sampler.py", line 308, in _env_runner summarize(unfiltered_obs))) File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/rllib/utils/debug.py", line 65, in summarize return _printer.pformat(_summarize(obj)) File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/rllib/utils/debug.py", line 70, in _summarize return {k: _summarize(v) for k, v in obj.items()} …snip… File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/ray/rllib/utils/debug.py", line 87, in _summarize obj.shape, obj.dtype, round(float(np.min(obj)), 3), File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 2618, in amin initial=initial) File "/home/sam/.virtualenvs/weird-env/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 86, in _wrapreduction return ufunc.reduce(obj, axis, dtype, out, **passkwargs) ValueError: zero-size array to reduction operation minimum which has no identity
17,859
ray-project/ray
ray-project__ray-5599
3e70daba740bc0d306aa12e3c1dc2917b53359b2
diff --git a/python/ray/tune/schedulers/pbt.py b/python/ray/tune/schedulers/pbt.py --- a/python/ray/tune/schedulers/pbt.py +++ b/python/ray/tune/schedulers/pbt.py @@ -13,6 +13,7 @@ from ray.tune.error import TuneError from ray.tune.result import TRAINING_ITERATION +from ray.tune.logger import _SafeFallbackEncoder from ray.tune.schedulers import FIFOScheduler, TrialScheduler from ray.tune.suggest.variant_generator import format_vars from ray.tune.trial import Trial, Checkpoint @@ -276,13 +277,13 @@ def _log_config_on_step(self, trial_state, new_state, trial, ] # Log to global file. with open(os.path.join(trial.local_dir, "pbt_global.txt"), "a+") as f: - f.write(json.dumps(policy) + "\n") + print(json.dumps(policy, cls=_SafeFallbackEncoder), file=f) # Overwrite state in target trial from trial_to_clone. if os.path.exists(trial_to_clone_path): shutil.copyfile(trial_to_clone_path, trial_path) # Log new exploit in target trial log. with open(trial_path, "a+") as f: - f.write(json.dumps(policy) + "\n") + f.write(json.dumps(policy, cls=_SafeFallbackEncoder) + "\n") def _exploit(self, trial_executor, trial, trial_to_clone): """Transfers perturbed state from trial_to_clone -> trial.
[tune] `tune.function` does not work with PTB scheduler <!-- General questions should be asked on the mailing list ray-dev@googlegroups.com. Questions about how to use Ray should be asked on [StackOverflow](https://stackoverflow.com/questions/tagged/ray). Before submitting an issue, please fill out the following form. --> ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**:macOS Moave 10.14.6 - **Ray installed from (source or binary)**: binary - **Ray version**:0.73 - **Python version**:3.6 - **Exact command to reproduce**: I simply took the `pbt_example.py` from the example folder and added a `tune.function` object in the config of `tune.run`: ```python """examples/pbt_example.py""" from ray.tune import function # ... def some_function(): # <== added this function return 42 run( PBTBenchmarkExample, name="pbt_test", scheduler=pbt, reuse_actors=True, verbose=False, **{ "stop": { "training_iteration": 2000, }, "num_samples": 4, "config": { "lr": 0.0001, # note: this parameter is perturbed but has no effect on # the model training in this example "some_other_factor": 1, "some_function": function(some_function) # <== added this line }, }) ``` ### Describe the problem Hi, it seems that there is a problem in dumping the function as json? When you execute the code you will also get the known error `AttributeError: 'NoneType' object has no attribute 'get_global_worker'` as discussed in #5042. Both errors do not occur when I remove the scheduler from the `tune.run` call. Would be great if you could look into this. ## Source code / logs ``` 2019-08-30 16:46:30,213 INFO pbt.py:82 -- [explore] perturbed config from {'lr': 0.0001, 'some_other_factor': 1, 'some_function': tune.function(<function some_function at 0x11fd31ae8>)} -> {'lr': 0.00012, 'some_other_factor': 2, 'some_function': tune.function(<function some_function at 0x11fd31ae8>)} 2019-08-30 16:46:30,213 INFO pbt.py:304 -- [exploit] transferring weights from trial PBTBenchmarkExample_3 (score 24.859665593890774) -> PBTBenchmarkExample_2 (score 1.1905894444680376) 2019-08-30 16:46:30,213 ERROR trial_runner.py:550 -- Error processing event. Traceback (most recent call last): File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/site-packages/ray/tune/trial_runner.py", line 520, in _process_trial self, trial, result) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/site-packages/ray/tune/schedulers/pbt.py", line 243, in on_trial_result self._exploit(trial_runner.trial_executor, trial, trial_to_clone) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/site-packages/ray/tune/schedulers/pbt.py", line 308, in _exploit trial_to_clone, new_config) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/site-packages/ray/tune/schedulers/pbt.py", line 277, in _log_config_on_step f.write(json.dumps(policy) + "\n") File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/json/encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'function' is not JSON serializable ```
2019-08-31T04:00:56Z
[]
[]
Traceback (most recent call last): File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/site-packages/ray/tune/trial_runner.py", line 520, in _process_trial self, trial, result) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/site-packages/ray/tune/schedulers/pbt.py", line 243, in on_trial_result self._exploit(trial_runner.trial_executor, trial, trial_to_clone) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/site-packages/ray/tune/schedulers/pbt.py", line 308, in _exploit trial_to_clone, new_config) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/site-packages/ray/tune/schedulers/pbt.py", line 277, in _log_config_on_step f.write(json.dumps(policy) + "\n") File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Users/XXXX/anaconda2/envs/dev-p36/lib/python3.6/json/encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'function' is not JSON serializable
17,873
ray-project/ray
ray-project__ray-5653
8a352a8e701978bfafa2f79d2a7e39c071227681
diff --git a/python/ray/tune/resources.py b/python/ray/tune/resources.py --- a/python/ray/tune/resources.py +++ b/python/ray/tune/resources.py @@ -5,11 +5,10 @@ from collections import namedtuple import logging import json +from numbers import Number # For compatibility under py2 to consider unicode as str from six import string_types -from numbers import Number - from ray.tune import TuneError logger = logging.getLogger(__name__) @@ -66,6 +65,23 @@ def __new__(cls, custom_resources.setdefault(value, 0) extra_custom_resources.setdefault(value, 0) + cpu = round(cpu, 2) + gpu = round(gpu, 2) + memory = round(memory, 2) + object_store_memory = round(object_store_memory, 2) + extra_cpu = round(extra_cpu, 2) + extra_gpu = round(extra_gpu, 2) + extra_memory = round(extra_memory, 2) + extra_object_store_memory = round(extra_object_store_memory, 2) + custom_resources = { + resource: round(value, 2) + for resource, value in custom_resources.items() + } + extra_custom_resources = { + resource: round(value, 2) + for resource, value in extra_custom_resources.items() + } + all_values = [ cpu, gpu, memory, object_store_memory, extra_cpu, extra_gpu, extra_memory, extra_object_store_memory
[tune] AssertionError: Resource invalid <!-- General questions should be asked on the mailing list ray-dev@googlegroups.com. Questions about how to use Ray should be asked on [StackOverflow](https://stackoverflow.com/questions/tagged/ray). Before submitting an issue, please fill out the following form. --> ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: Ubuntu 16.04 - **Ray installed from (source or binary)**: pip install https://s3-us-west-2.amazonaws.com/ray-wheels/latest/ray-0.8.0.dev4-cp36-cp36m-manylinux1_x86_64.whl - **Ray version**: 0.8.0.dev4 - **Python version**: 3.6.7 - **Exact command to reproduce**: <!-- You can obtain the Ray version with python -c "import ray; print(ray.__version__)" --> ### Describe the problem <!-- Describe the problem clearly here. --> I run 5 trials with ray.tune. In one of the trials (each time), an error occurs at the end of training: `AssertionError: Resource invalid: Resources(cpu=3, gpu=0.33, memory=0, object_store_memory=0, extra_cpu=0, extra_gpu=0, extra_memory=0, extra_object_store_memory=0, custom_resources={}, extra_custom_resources={})`. When I trace back the error, I end up in the following function (ray/tune/resources.py): ``` def is_nonnegative(self): all_values = [self.cpu, self.gpu, self.extra_cpu, self.extra_gpu] all_values += list(self.custom_resources.values()) all_values += list(self.extra_custom_resources.values()) return all(v >= 0 for v in all_values) ``` It seems `custom_resources` and `extra_custom_resources` are not defined. It is weird that the error only occurs in one run... Is this a bug, or any suggestions on how to fix? ### Source code / logs <!-- Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached. Try to provide a reproducible test case that is the bare minimum necessary to generate the problem. --> __This is how I call `tune.run`__ ``` tune.run( ModelTrainerMT, resources_per_trial={ 'cpu': config['ncpu'], 'gpu': config['ngpu'], }, num_samples=1, config=best_config, local_dir=store, raise_on_failed_trial=True, verbose=1, with_server=False, ray_auto_init=False, scheduler=early_stopping_scheduler, loggers=[JsonLogger, CSVLogger], checkpoint_at_end=True, reuse_actors=True, stop={'epoch': 2 if args.test else config['max_t']} ) ``` __Traceback__ ``` 2019-09-06 09:56:45,526 ERROR trial_runner.py:557 -- Error processing event. Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/ray/tune/trial_runner.py", line 552, in _process_trial self.trial_executor.stop_trial(trial) File "/opt/conda/lib/python3.6/site-packages/ray/tune/ray_trial_executor.py", line 246, in stop_trial self._return_resources(trial.resources) File "/opt/conda/lib/python3.6/site-packages/ray/tune/ray_trial_executor.py", line 388, in _return_resources "Resource invalid: {}".format(resources)) AssertionError: Resource invalid: Resources(cpu=3, gpu=0.33, memory=0, object_store_memory=0, extra_cpu=0, extra_gpu=0, extra_memory=0, extra_object_store_memory=0, custom_resources={}, extra_custom_resources={}) ```
@richardliaw
2019-09-07T05:26:29Z
[]
[]
Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/ray/tune/trial_runner.py", line 552, in _process_trial self.trial_executor.stop_trial(trial) File "/opt/conda/lib/python3.6/site-packages/ray/tune/ray_trial_executor.py", line 246, in stop_trial self._return_resources(trial.resources) File "/opt/conda/lib/python3.6/site-packages/ray/tune/ray_trial_executor.py", line 388, in _return_resources "Resource invalid: {}".format(resources)) AssertionError: Resource invalid: Resources(cpu=3, gpu=0.33, memory=0, object_store_memory=0, extra_cpu=0, extra_gpu=0, extra_memory=0, extra_object_store_memory=0, custom_resources={}, extra_custom_resources={})
17,876
ray-project/ray
ray-project__ray-5687
336aef1774aecb3db41f6e2c1d35f28e41279e1a
diff --git a/rllib/agents/ppo/ppo.py b/rllib/agents/ppo/ppo.py --- a/rllib/agents/ppo/ppo.py +++ b/rllib/agents/ppo/ppo.py @@ -128,6 +128,8 @@ def warn_about_bad_reward_scales(trainer, result): def validate_config(config): if config["entropy_coeff"] < 0: raise DeprecationWarning("entropy_coeff must be >= 0") + if isinstance(config["entropy_coeff"], int): + config["entropy_coeff"] = float(config["entropy_coeff"]) if config["sgd_minibatch_size"] > config["train_batch_size"]: raise ValueError( "Minibatch size {} must be <= train batch size {}.".format(
[rllib] Integer entropy coeff cannot be passed in <!-- General questions should be asked on the mailing list ray-dev@googlegroups.com. Questions about how to use Ray should be asked on [StackOverflow](https://stackoverflow.com/questions/tagged/ray). Before submitting an issue, please fill out the following form. --> ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: Steropes - **Ray installed from (source or binary)**: pip install -U <latest whl> - **Ray version**: nightly - **Python version**: 3.7 - **Exact command to reproduce**: Pass integer value of entropy_coeff into run() with PPO <!-- You can obtain the Ray version with python -c "import ray; print(ray.__version__)" --> ### Describe the problem <!-- Describe the problem clearly here. --> ### Source code / logs <!-- Include any logs or source code that would be helpful to diagnose the problem. If including tracebacks, please include the full traceback. Large logs and files should be attached. Try to provide a reproducible test case that is the bare minimum necessary to generate the problem. --> ``` 2019-09-11 00:11:50,889 ERROR trial_runner.py:552 -- Error processing event. Traceback (most recent call last): File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/tune/trial_runner.py", line 498, in _process_trial result = self.trial_executor.fetch_result(trial) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/tune/ray_trial_executor.py", line 347, in fetch_result result = ray.get(trial_future[0]) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/worker.py", line 2340, in get raise value ray.exceptions.RayTaskError: ray_PPO:train() (pid=11050, host=steropes) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py", line 527, in _apply_op_helper preferred_dtype=default_dtype) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 1224, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/ops.py", line 1018, in _TensorTensorConversionFunction (dtype.name, t.dtype.name, str(t))) ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("default_policy/Sum_5:0", shape=(?,), dtype=float32)' During handling of the above exception, another exception occurred: ray_PPO:train() (pid=11050, host=steropes) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/agents/trainer_template.py", line 90, in __init__ Trainer.__init__(self, config, env, logger_creator) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/agents/trainer.py", line 366, in __init__ Trainable.__init__(self, config, logger_creator) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/tune/trainable.py", line 99, in __init__ self._setup(copy.deepcopy(self.config)) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/agents/trainer.py", line 486, in _setup self._init(self.config, self.env_creator) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/agents/trainer_template.py", line 109, in _init self.config["num_workers"]) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/agents/trainer.py", line 531, in _make_workers logdir=self.logdir) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/evaluation/worker_set.py", line 64, in __init__ RolloutWorker, env_creator, policy, 0, self._local_config) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/evaluation/worker_set.py", line 220, in _make_worker _fake_sampler=config.get("_fake_sampler", False)) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/evaluation/rollout_worker.py", line 348, in __init__ self._build_policy_map(policy_dict, policy_config) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/evaluation/rollout_worker.py", line 762, in _build_policy_map policy_map[name] = cls(obs_space, act_space, merged_conf) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/policy/tf_policy_template.py", line 143, in __init__ obs_include_prev_action_reward=obs_include_prev_action_reward) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/policy/dynamic_tf_policy.py", line 196, in __init__ self._initialize_loss() File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/policy/dynamic_tf_policy.py", line 337, in _initialize_loss loss = self._do_loss_init(train_batch) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/policy/dynamic_tf_policy.py", line 349, in _do_loss_init loss = self._loss_fn(self, self.model, self._dist_class, train_batch) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/agents/ppo/ppo_policy.py", line 146, in ppo_surrogate_loss model_config=policy.config["model"]) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/rllib/agents/ppo/ppo_policy.py", line 106, in __init__ vf_loss_coeff * vf_loss - entropy_coeff * curr_entropy) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/variables.py", line 1045, in _run_op return tensor_oper(a.value(), *args, **kwargs) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py", line 884, in binary_op_wrapper return func(x, y, name=name) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/math_ops.py", line 1180, in _mul_dispatch return gen_math_ops.mul(x, y, name=name) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/tensorflow/python/ops/gen_math_ops.py", line 6490, in mul "Mul", x=x, y=y, name=name) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/op_def_library.py", line 563, in _apply_op_helper inferred_from[input_arg.type_attr])) TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type int32 of argument 'x'. ```
2019-09-11T07:13:50Z
[]
[]
Traceback (most recent call last): File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/tune/trial_runner.py", line 498, in _process_trial result = self.trial_executor.fetch_result(trial) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/tune/ray_trial_executor.py", line 347, in fetch_result result = ray.get(trial_future[0]) File "/data/ashwineep/anaconda3/lib/python3.7/site-packages/ray/worker.py", line 2340, in get raise value ray.exceptions.RayTaskError: ray_PPO:train() (pid=11050, host=steropes)
17,879
ray-project/ray
ray-project__ray-5863
785670bc18a8595219c96e9512192922fafcf510
diff --git a/python/ray/actor.py b/python/ray/actor.py --- a/python/ray/actor.py +++ b/python/ray/actor.py @@ -369,9 +369,7 @@ def _remote(self, # Instead, instantiate the actor locally and add it to the worker's # dictionary if worker.mode == ray.LOCAL_MODE: - actor_id = ActorID.of(worker.current_job_id, - worker.current_task_id, - worker.task_context.task_index + 1) + actor_id = ActorID.from_random() worker.actors[actor_id] = meta.modified_class( *copy.deepcopy(args), **copy.deepcopy(kwargs)) core_handle = ray._raylet.ActorHandle(
[local mode] Actors are not handled correctly The below fails with: ```bash Traceback (most recent call last): File "/Users/rliaw/Research/riselab/ray/doc/examples/parameter_server/failure.py", line 35, in <module> accuracies = run_sync_parameter_server() File "/Users/rliaw/Research/riselab/ray/doc/examples/parameter_server/failure.py", line 32, in run_sync_parameter_server current_weights = ps.get_weights.remote() File "/Users/rliaw/miniconda3/lib/python3.7/site-packages/ray/actor.py", line 148, in remote return self._remote(args, kwargs) File "/Users/rliaw/miniconda3/lib/python3.7/site-packages/ray/actor.py", line 169, in _remote return invocation(args, kwargs) File "/Users/rliaw/miniconda3/lib/python3.7/site-packages/ray/actor.py", line 163, in invocation num_return_vals=num_return_vals) File "/Users/rliaw/miniconda3/lib/python3.7/site-packages/ray/actor.py", line 588, in _actor_method_call function = getattr(worker.actors[self._ray_actor_id], method_name) AttributeError: 'DataWorker' object has no attribute 'get_weights' ``` ```python import ray @ray.remote class ParameterServer(object): def __init__(self, learning_rate): pass def apply_gradients(self, *gradients): pass def get_weights(self): pass @ray.remote class DataWorker(object): def __init__(self): pass def compute_gradient_on_batch(self, data, target): pass def compute_gradients(self, weights): pass def run_sync_parameter_server(): iterations = 50 num_workers = 2 ps = ParameterServer.remote(1e-4 * num_workers) # Create workers. workers = [DataWorker.remote() for i in range(num_workers)] current_weights = ps.get_weights.remote() ray.init(ignore_reinit_error=True, local_mode=True) accuracies = run_sync_parameter_server() ```
cc @edoakes I'll take a look into this. I get a similar error in this test case. ```python import ray from ray import tune config = {"env": "CartPole-v1"} ray.init(local_mode=True) tune.run("PPO", config=config) ``` ``` Traceback (most recent call last): File "/home/matt/Code/ray/python/ray/tune/trial_runner.py", line 506, in _process_trial result = self.trial_executor.fetch_result(trial) File "/home/matt/Code/ray/python/ray/tune/ray_trial_executor.py", line 347, in fetch_result result = ray.get(trial_future[0]) File "/home/matt/Code/ray/python/ray/worker.py", line 2349, in get raise value ray.exceptions.RayTaskError: python test.py (pid=32468, host=Rocko2) File "/home/matt/Code/ray/python/ray/local_mode_manager.py", line 55, in execute results = function(*copy.deepcopy(args)) File "/home/matt/Code/ray/python/ray/rllib/agents/trainer.py", line 395, in train w.set_global_vars.remote(self.global_vars) File "/home/matt/Code/ray/python/ray/actor.py", line 148, in remote return self._remote(args, kwargs) File "/home/matt/Code/ray/python/ray/actor.py", line 169, in _remote return invocation(args, kwargs) File "/home/matt/Code/ray/python/ray/actor.py", line 163, in invocation num_return_vals=num_return_vals) File "/home/matt/Code/ray/python/ray/actor.py", line 588, in _actor_method_call function = getattr(worker.actors[self._ray_actor_id], method_name) AttributeError: 'PPO' object has no attribute 'set_global_vars' ``` > I get a similar error in this test case. > > ```python > import ray > from ray import tune > config = {"env": "CartPole-v1"} > ray.init(local_mode=True) > tune.run("PPO", config=config) > ``` > > ``` > Traceback (most recent call last): > File "/home/matt/Code/ray/python/ray/tune/trial_runner.py", line 506, in _process_trial > result = self.trial_executor.fetch_result(trial) > File "/home/matt/Code/ray/python/ray/tune/ray_trial_executor.py", line 347, in fetch_result > result = ray.get(trial_future[0]) > File "/home/matt/Code/ray/python/ray/worker.py", line 2349, in get > raise value > ray.exceptions.RayTaskError: python test.py (pid=32468, host=Rocko2) > File "/home/matt/Code/ray/python/ray/local_mode_manager.py", line 55, in execute > results = function(*copy.deepcopy(args)) > File "/home/matt/Code/ray/python/ray/rllib/agents/trainer.py", line 395, in train > w.set_global_vars.remote(self.global_vars) > File "/home/matt/Code/ray/python/ray/actor.py", line 148, in remote > return self._remote(args, kwargs) > File "/home/matt/Code/ray/python/ray/actor.py", line 169, in _remote > return invocation(args, kwargs) > File "/home/matt/Code/ray/python/ray/actor.py", line 163, in invocation > num_return_vals=num_return_vals) > File "/home/matt/Code/ray/python/ray/actor.py", line 588, in _actor_method_call > function = getattr(worker.actors[self._ray_actor_id], method_name) > AttributeError: 'PPO' object has no attribute 'set_global_vars' > ``` I'm getting the same error with: ``` ray.init(num_cpus=N_CPUS, local_mode=True) # defining dictionary for the experiment experiment_params = dict( run="PPO", # must be the same as the default config env=gym_name, config={**ppo_config}, checkpoint_freq=20, checkpoint_at_end=True, max_failures=999, stop={"training_iteration": 200, }, # stop conditions ) experiment_params = {params["exp_tag"]: experiment_params} # running the experiment trials = run_experiments(experiment_params) ``` With the following Traceback: ``` ray.exceptions.RayTaskError: /anaconda3/envs/dmas/bin/python /Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py --mode=client --port=49411 (pid=1002, host=client-145-120-37-77.surfnet.eduroam.rug.nl) File "/anaconda3/envs/dmas/lib/python3.6/site-packages/ray/local_mode_manager.py", line 55, in execute results = function(*copy.deepcopy(args)) File "/anaconda3/envs/dmas/lib/python3.6/site-packages/ray/rllib/agents/trainer.py", line 395, in train w.set_global_vars.remote(self.global_vars) File "/anaconda3/envs/dmas/lib/python3.6/site-packages/ray/actor.py", line 148, in remote return self._remote(args, kwargs) File "/anaconda3/envs/dmas/lib/python3.6/site-packages/ray/actor.py", line 169, in _remote return invocation(args, kwargs) File "/anaconda3/envs/dmas/lib/python3.6/site-packages/ray/actor.py", line 163, in invocation num_return_vals=num_return_vals) File "/anaconda3/envs/dmas/lib/python3.6/site-packages/ray/actor.py", line 548, in _actor_method_call function = getattr(worker.actors[self._ray_actor_id], method_name) AttributeError: 'PPO' object has no attribute 'set_global_vars' ```
2019-10-08T17:40:27Z
[]
[]
Traceback (most recent call last): File "/Users/rliaw/Research/riselab/ray/doc/examples/parameter_server/failure.py", line 35, in <module> accuracies = run_sync_parameter_server() File "/Users/rliaw/Research/riselab/ray/doc/examples/parameter_server/failure.py", line 32, in run_sync_parameter_server current_weights = ps.get_weights.remote() File "/Users/rliaw/miniconda3/lib/python3.7/site-packages/ray/actor.py", line 148, in remote return self._remote(args, kwargs) File "/Users/rliaw/miniconda3/lib/python3.7/site-packages/ray/actor.py", line 169, in _remote return invocation(args, kwargs) File "/Users/rliaw/miniconda3/lib/python3.7/site-packages/ray/actor.py", line 163, in invocation num_return_vals=num_return_vals) File "/Users/rliaw/miniconda3/lib/python3.7/site-packages/ray/actor.py", line 588, in _actor_method_call function = getattr(worker.actors[self._ray_actor_id], method_name) AttributeError: 'DataWorker' object has no attribute 'get_weights'
17,883
ray-project/ray
ray-project__ray-5971
252a5d13ed129107584a26766ac934d336e4b755
diff --git a/python/ray/tune/experiment.py b/python/ray/tune/experiment.py --- a/python/ray/tune/experiment.py +++ b/python/ray/tune/experiment.py @@ -102,9 +102,9 @@ def __init__(self, "criteria must take exactly 2 parameters.".format(stop)) config = config or {} - run_identifier = Experiment._register_if_needed(run) + self._run_identifier = Experiment._register_if_needed(run) spec = { - "run": run_identifier, + "run": self._run_identifier, "stop": stop, "config": config, "resources_per_trial": resources_per_trial, @@ -125,7 +125,7 @@ def __init__(self, if restore else None } - self.name = name or run_identifier + self.name = name or self._run_identifier self.spec = spec @classmethod @@ -202,6 +202,11 @@ def remote_checkpoint_dir(self): if self.spec["upload_dir"]: return os.path.join(self.spec["upload_dir"], self.name) + @property + def run_identifier(self): + """Returns a string representing the trainable identifier.""" + return self._run_identifier + def convert_to_experiment_list(experiments): """Produces a list of Experiment objects. diff --git a/python/ray/tune/tune.py b/python/ray/tune/tune.py --- a/python/ray/tune/tune.py +++ b/python/ray/tune/tune.py @@ -4,6 +4,7 @@ import logging import time +import six from ray.tune.error import TuneError from ray.tune.experiment import convert_to_experiment_list, Experiment @@ -45,6 +46,9 @@ def _make_scheduler(args): def _check_default_resources_override(run_identifier): + if not isinstance(run_identifier, six.string_types): + # If obscure dtype, assume it is overriden. + return True trainable_cls = get_trainable_cls(run_identifier) return hasattr(trainable_cls, "default_resource_request") and ( trainable_cls.default_resource_request.__code__ != @@ -265,7 +269,7 @@ def run(run_or_experiment, dict) and "gpu" in resources_per_trial: # "gpu" is manually set. pass - elif _check_default_resources_override(run_identifier): + elif _check_default_resources_override(experiment.run_identifier): # "default_resources" is manually overriden. pass else:
Undefined Reference To "run_identifier" on GPU Machine With tune.Experiment On the latest nightly build, passing a `tune.Experiment` into `tune.Run` on a GPU machine results in an undefined reference to `run_identifier`. This occurs because `run_identifier` is defined conditionally [here](https://github.com/ray-project/ray/blob/91acecc9f9eb8d1a7e9fe651bd50e3b2d68ecee2/python/ray/tune/tune.py#L214). The `run_identifier` reference occurs on [this line](https://github.com/ray-project/ray/blob/91acecc9f9eb8d1a7e9fe651bd50e3b2d68ecee2/python/ray/tune/tune.py#L268). Traceback for the error: ``` 2019-10-22 06:57:15,904 DEBUG registry.py:59 -- Detected class for trainable. 2019-10-22 06:57:15,906 DEBUG tune.py:236 -- Ignoring some parameters passed into tune.run. 2019-10-22 06:57:15,909 DEBUG trial_runner.py:175 -- Starting a new experiment. Traceback (most recent call last): File "/home/steven/res/railrl-private/railrl/launchers/ray/local_launch.py", line 94, in <module> launch_local_experiment(**local_launch_variant) File "/home/steven/res/railrl-private/railrl/launchers/ray/local_launch.py", line 82, in launch_local_experiment queue_trials=True, File "/env/lib/python3.5/site-packages/ray/tune/tune.py", line 268, in run elif _check_default_resources_override(run_identifier): UnboundLocalError: local variable 'run_identifier' referenced before assignment ```
2019-10-22T07:36:32Z
[]
[]
Traceback (most recent call last): File "/home/steven/res/railrl-private/railrl/launchers/ray/local_launch.py", line 94, in <module> launch_local_experiment(**local_launch_variant) File "/home/steven/res/railrl-private/railrl/launchers/ray/local_launch.py", line 82, in launch_local_experiment queue_trials=True, File "/env/lib/python3.5/site-packages/ray/tune/tune.py", line 268, in run elif _check_default_resources_override(run_identifier): UnboundLocalError: local variable 'run_identifier' referenced before assignment
17,886
ray-project/ray
ray-project__ray-6170
7d33e9949b942acde92db6698abdb6b409c0648c
diff --git a/python/ray/local_mode_manager.py b/python/ray/local_mode_manager.py --- a/python/ray/local_mode_manager.py +++ b/python/ray/local_mode_manager.py @@ -5,6 +5,7 @@ import copy import traceback +import ray from ray import ObjectID from ray.utils import format_error_message from ray.exceptions import RayTaskError @@ -20,7 +21,18 @@ class LocalModeObjectID(ObjectID): it equates to the object not existing in the object store. This is necessary because None is a valid object value. """ - pass + + def __copy__(self): + new = LocalModeObjectID(self.binary()) + if hasattr(self, "value"): + new.value = self.value + return new + + def __deepcopy__(self, memo=None): + new = LocalModeObjectID(self.binary()) + if hasattr(self, "value"): + new.value = self.value + return new class LocalModeManager(object): @@ -49,23 +61,37 @@ def execute(self, function, function_name, args, kwargs, num_return_vals): Returns: LocalModeObjectIDs corresponding to the function return values. """ - object_ids = [ + return_ids = [ LocalModeObjectID.from_random() for _ in range(num_return_vals) ] + new_args = [] + for i, arg in enumerate(args): + if isinstance(arg, ObjectID): + new_args.append(ray.get(arg)) + else: + new_args.append(copy.deepcopy(arg)) + + new_kwargs = {} + for k, v in kwargs.items(): + if isinstance(v, ObjectID): + new_kwargs[k] = ray.get(v) + else: + new_kwargs[k] = copy.deepcopy(v) + try: - results = function(*copy.deepcopy(args), **copy.deepcopy(kwargs)) + results = function(*new_args, **new_kwargs) if num_return_vals == 1: - object_ids[0].value = results + return_ids[0].value = results else: - for object_id, result in zip(object_ids, results): + for object_id, result in zip(return_ids, results): object_id.value = result except Exception as e: backtrace = format_error_message(traceback.format_exc()) task_error = RayTaskError(function_name, backtrace, e.__class__) - for object_id in object_ids: + for object_id in return_ids: object_id.value = task_error - return object_ids + return return_ids def put_object(self, value): """Store an object in the emulated object store.
Passing ObjectID as a function argument in local_mode is broken ### System information - **OS Platform and Distribution**: Ubuntu 18.04 - **Ray installed from (source or binary)**: binary - **Ray version**: 0.8.0.dev6 - **Python version**: 3.7 - **Exact command to reproduce**: see below ### Describe the problem The argument passing behavior with local_mode=True vs False seems to be different. When I run the code snippet below: ```import ray ray.init(local_mode=True) # Replace with False to get a working example @ray.remote def remote_function(x): obj = x['a'] return ray.get(obj) a = ray.put(42) d = {'a': a} result = remote_function.remote(d) print(ray.get(result)) ``` With local_mode=False I get output `42`, as expected. With local_mode=True I get the following error: ``` Traceback (most recent call last): File "/home/alex/all/projects/doom-neurobot/playground/ray_local_mode_bug.py", line 13, in <module> print(ray.get(result)) File "/home/alex/miniconda3/envs/doom-rl/lib/python3.7/site-packages/ray/worker.py", line 2194, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError(KeyError): /home/alex/miniconda3/envs/doom-rl/bin/python /home/alex/all/projects/doom-neurobot/playground/ray_local_mode_bug.py (pid=2449, ip=10.136.109.38) File "/home/alex/miniconda3/envs/doom-rl/lib/python3.7/site-packages/ray/local_mode_manager.py", line 55, in execute results = function(*copy.deepcopy(args)) File "/home/alex/all/projects/doom-neurobot/playground/ray_local_mode_bug.py", line 7, in remote_function return ray.get(obj) File "/home/alex/miniconda3/envs/doom-rl/lib/python3.7/site-packages/ray/local_mode_manager.py", line 105, in get_objects raise KeyError("Value for {} not found".format(object_id)) KeyError: 'Value for LocalModeObjectID(89f92e430883458c8107c10ed53eb35b26099831) not found' ``` It looks like the LocalObjectID instance inside `d` loses it's field `value` when it gets deep copied during the "remote" function call (currently it's `local_mode_manager.py:55`). It's hard to tell why exactly that happens, looks like a bug.
Indeed, this example seems to confirm that it might be a `deepcopy` problem: ``` import ray ray.init(local_mode=True) a = ray.put(42) from copy import deepcopy a_copy = deepcopy(a) print(ray.get(a)) print(ray.get(a_copy)) ``` I get `42` printed and then an error upon attempting to `ray.get(a_copy)`. Is this intended? Related to #5853? cc @edoakes It is related, and I agree that local_mode should mimic normal operation as closely as possible. Although probably there's an easier fix for this small issue. Fixed it temporarily by implementing `__deepcopy__` on `LocalModeObjectID`: ``` def __deepcopy__(self, memodict={}): obj_copy = copy.copy(self) content_copy = copy.deepcopy(self.__dict__, memodict) obj_copy.__dict__.update(content_copy) return obj_copy ```
2019-11-15T20:14:50Z
[]
[]
Traceback (most recent call last): File "/home/alex/all/projects/doom-neurobot/playground/ray_local_mode_bug.py", line 13, in <module> print(ray.get(result)) File "/home/alex/miniconda3/envs/doom-rl/lib/python3.7/site-packages/ray/worker.py", line 2194, in get raise value.as_instanceof_cause() ray.exceptions.RayTaskError(KeyError): /home/alex/miniconda3/envs/doom-rl/bin/python /home/alex/all/projects/doom-neurobot/playground/ray_local_mode_bug.py (pid=2449, ip=10.136.109.38)
17,889
ray-project/ray
ray-project__ray-6634
3e0f07468fb117bfbe25feb815c83f02028284b7
diff --git a/doc/examples/parameter_server/async_parameter_server.py b/doc/examples/parameter_server/async_parameter_server.py deleted file mode 100644 --- a/doc/examples/parameter_server/async_parameter_server.py +++ /dev/null @@ -1,80 +0,0 @@ -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import argparse -import time - -import ray -import model - -parser = argparse.ArgumentParser(description="Run the asynchronous parameter " - "server example.") -parser.add_argument("--num-workers", default=4, type=int, - help="The number of workers to use.") -parser.add_argument("--redis-address", default=None, type=str, - help="The Redis address of the cluster.") - - -@ray.remote -class ParameterServer(object): - def __init__(self, keys, values): - # These values will be mutated, so we must create a copy that is not - # backed by the object store. - values = [value.copy() for value in values] - self.weights = dict(zip(keys, values)) - - def push(self, keys, values): - for key, value in zip(keys, values): - self.weights[key] += value - - def pull(self, keys): - return [self.weights[key] for key in keys] - - -@ray.remote -def worker_task(ps, worker_index, batch_size=50): - # Download MNIST. - mnist = model.download_mnist_retry(seed=worker_index) - - # Initialize the model. - net = model.SimpleCNN() - keys = net.get_weights()[0] - - while True: - # Get the current weights from the parameter server. - weights = ray.get(ps.pull.remote(keys)) - net.set_weights(keys, weights) - - # Compute an update and push it to the parameter server. - xs, ys = mnist.train.next_batch(batch_size) - gradients = net.compute_update(xs, ys) - ps.push.remote(keys, gradients) - - -if __name__ == "__main__": - args = parser.parse_args() - - ray.init(redis_address=args.redis_address) - - # Create a parameter server with some random weights. - net = model.SimpleCNN() - all_keys, all_values = net.get_weights() - ps = ParameterServer.remote(all_keys, all_values) - - # Start some training tasks. - worker_tasks = [worker_task.remote(ps, i) for i in range(args.num_workers)] - - # Download MNIST. - mnist = model.download_mnist_retry() - - i = 0 - while True: - # Get and evaluate the current model. - current_weights = ray.get(ps.pull.remote(all_keys)) - net.set_weights(all_keys, current_weights) - test_xs, test_ys = mnist.test.next_batch(1000) - accuracy = net.compute_accuracy(test_xs, test_ys) - print("Iteration {}: accuracy is {}".format(i, accuracy)) - i += 1 - time.sleep(1) diff --git a/doc/examples/parameter_server/model.py b/doc/examples/parameter_server/model.py deleted file mode 100644 --- a/doc/examples/parameter_server/model.py +++ /dev/null @@ -1,203 +0,0 @@ -# Most of the tensorflow code is adapted from Tensorflow's tutorial on using -# CNNs to train MNIST -# https://www.tensorflow.org/get_started/mnist/pros#build-a-multilayer-convolutional-network. # noqa: E501 - -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import time - -import tensorflow as tf -from tensorflow.examples.tutorials.mnist import input_data - -import ray -import ray.experimental.tf_utils - - -def download_mnist_retry(seed=0, max_num_retries=20): - for _ in range(max_num_retries): - try: - return input_data.read_data_sets( - "MNIST_data", one_hot=True, seed=seed) - except tf.errors.AlreadyExistsError: - time.sleep(1) - raise Exception("Failed to download MNIST.") - - -class SimpleCNN(object): - def __init__(self, learning_rate=1e-4): - with tf.Graph().as_default(): - - # Create the model - self.x = tf.placeholder(tf.float32, [None, 784]) - - # Define loss and optimizer - self.y_ = tf.placeholder(tf.float32, [None, 10]) - - # Build the graph for the deep net - self.y_conv, self.keep_prob = deepnn(self.x) - - with tf.name_scope("loss"): - cross_entropy = tf.nn.softmax_cross_entropy_with_logits( - labels=self.y_, logits=self.y_conv) - self.cross_entropy = tf.reduce_mean(cross_entropy) - - with tf.name_scope("adam_optimizer"): - self.optimizer = tf.train.AdamOptimizer(learning_rate) - self.train_step = self.optimizer.minimize(self.cross_entropy) - - with tf.name_scope("accuracy"): - correct_prediction = tf.equal( - tf.argmax(self.y_conv, 1), tf.argmax(self.y_, 1)) - correct_prediction = tf.cast(correct_prediction, tf.float32) - self.accuracy = tf.reduce_mean(correct_prediction) - - self.sess = tf.Session( - config=tf.ConfigProto( - intra_op_parallelism_threads=1, - inter_op_parallelism_threads=1)) - self.sess.run(tf.global_variables_initializer()) - - # Helper values. - - self.variables = ray.experimental.tf_utils.TensorFlowVariables( - self.cross_entropy, self.sess) - - self.grads = self.optimizer.compute_gradients(self.cross_entropy) - self.grads_placeholder = [(tf.placeholder( - "float", shape=grad[1].get_shape()), grad[1]) - for grad in self.grads] - self.apply_grads_placeholder = self.optimizer.apply_gradients( - self.grads_placeholder) - - def compute_update(self, x, y): - # TODO(rkn): Computing the weights before and after the training step - # and taking the diff is awful. - weights = self.get_weights()[1] - self.sess.run( - self.train_step, - feed_dict={ - self.x: x, - self.y_: y, - self.keep_prob: 0.5 - }) - new_weights = self.get_weights()[1] - return [x - y for x, y in zip(new_weights, weights)] - - def compute_gradients(self, x, y): - return self.sess.run( - [grad[0] for grad in self.grads], - feed_dict={ - self.x: x, - self.y_: y, - self.keep_prob: 0.5 - }) - - def apply_gradients(self, gradients): - feed_dict = {} - for i in range(len(self.grads_placeholder)): - feed_dict[self.grads_placeholder[i][0]] = gradients[i] - self.sess.run(self.apply_grads_placeholder, feed_dict=feed_dict) - - def compute_accuracy(self, x, y): - return self.sess.run( - self.accuracy, - feed_dict={ - self.x: x, - self.y_: y, - self.keep_prob: 1.0 - }) - - def set_weights(self, variable_names, weights): - self.variables.set_weights(dict(zip(variable_names, weights))) - - def get_weights(self): - weights = self.variables.get_weights() - return list(weights.keys()), list(weights.values()) - - -def deepnn(x): - """deepnn builds the graph for a deep net for classifying digits. - - Args: - x: an input tensor with the dimensions (N_examples, 784), where 784 is - the number of pixels in a standard MNIST image. - - Returns: - A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with - values equal to the logits of classifying the digit into one of 10 - classes (the digits 0-9). keep_prob is a scalar placeholder for the - probability of dropout. - """ - # Reshape to use within a convolutional neural net. - # Last dimension is for "features" - there is only one here, since images - # are grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc. - with tf.name_scope("reshape"): - x_image = tf.reshape(x, [-1, 28, 28, 1]) - - # First convolutional layer - maps one grayscale image to 32 feature maps. - with tf.name_scope("conv1"): - W_conv1 = weight_variable([5, 5, 1, 32]) - b_conv1 = bias_variable([32]) - h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) - - # Pooling layer - downsamples by 2X. - with tf.name_scope("pool1"): - h_pool1 = max_pool_2x2(h_conv1) - - # Second convolutional layer -- maps 32 feature maps to 64. - with tf.name_scope("conv2"): - W_conv2 = weight_variable([5, 5, 32, 64]) - b_conv2 = bias_variable([64]) - h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) - - # Second pooling layer. - with tf.name_scope("pool2"): - h_pool2 = max_pool_2x2(h_conv2) - - # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image - # is down to 7x7x64 feature maps -- maps this to 1024 features. - with tf.name_scope("fc1"): - W_fc1 = weight_variable([7 * 7 * 64, 1024]) - b_fc1 = bias_variable([1024]) - - h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) - h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) - - # Dropout - controls the complexity of the model, prevents co-adaptation of - # features. - with tf.name_scope("dropout"): - keep_prob = tf.placeholder(tf.float32) - h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) - - # Map the 1024 features to 10 classes, one for each digit - with tf.name_scope("fc2"): - W_fc2 = weight_variable([1024, 10]) - b_fc2 = bias_variable([10]) - - y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 - return y_conv, keep_prob - - -def conv2d(x, W): - """conv2d returns a 2d convolution layer with full stride.""" - return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding="SAME") - - -def max_pool_2x2(x): - """max_pool_2x2 downsamples a feature map by 2X.""" - return tf.nn.max_pool( - x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") - - -def weight_variable(shape): - """weight_variable generates a weight variable of a given shape.""" - initial = tf.truncated_normal(shape, stddev=0.1) - return tf.Variable(initial) - - -def bias_variable(shape): - """bias_variable generates a bias variable of a given shape.""" - initial = tf.constant(0.1, shape=shape) - return tf.Variable(initial) diff --git a/doc/examples/parameter_server/sync_parameter_server.py b/doc/examples/parameter_server/sync_parameter_server.py deleted file mode 100644 --- a/doc/examples/parameter_server/sync_parameter_server.py +++ /dev/null @@ -1,76 +0,0 @@ -from __future__ import absolute_import -from __future__ import division -from __future__ import print_function - -import argparse -import numpy as np - -import ray -import model - -parser = argparse.ArgumentParser(description="Run the synchronous parameter " - "server example.") -parser.add_argument("--num-workers", default=4, type=int, - help="The number of workers to use.") -parser.add_argument("--redis-address", default=None, type=str, - help="The Redis address of the cluster.") - - -@ray.remote -class ParameterServer(object): - def __init__(self, learning_rate): - self.net = model.SimpleCNN(learning_rate=learning_rate) - - def apply_gradients(self, *gradients): - self.net.apply_gradients(np.mean(gradients, axis=0)) - return self.net.variables.get_flat() - - def get_weights(self): - return self.net.variables.get_flat() - - -@ray.remote -class Worker(object): - def __init__(self, worker_index, batch_size=50): - self.worker_index = worker_index - self.batch_size = batch_size - self.mnist = model.download_mnist_retry(seed=worker_index) - self.net = model.SimpleCNN() - - def compute_gradients(self, weights): - self.net.variables.set_flat(weights) - xs, ys = self.mnist.train.next_batch(self.batch_size) - return self.net.compute_gradients(xs, ys) - - -if __name__ == "__main__": - args = parser.parse_args() - - ray.init(redis_address=args.redis_address) - - # Create a parameter server. - net = model.SimpleCNN() - ps = ParameterServer.remote(1e-4 * args.num_workers) - - # Create workers. - workers = [Worker.remote(worker_index) - for worker_index in range(args.num_workers)] - - # Download MNIST. - mnist = model.download_mnist_retry() - - i = 0 - current_weights = ps.get_weights.remote() - while True: - # Compute and apply gradients. - gradients = [worker.compute_gradients.remote(current_weights) - for worker in workers] - current_weights = ps.apply_gradients.remote(*gradients) - - if i % 10 == 0: - # Evaluate the current model. - net.variables.set_flat(ray.get(current_weights)) - test_xs, test_ys = mnist.test.next_batch(1000) - accuracy = net.compute_accuracy(test_xs, test_ys) - print("Iteration {}: accuracy is {}".format(i, accuracy)) - i += 1
Some examples no longer run ### What is the problem? *Ray version and other system information (Python version, TensorFlow version, OS):* - Using the current Ray master 3e0f07468fb117bfbe25feb815c83f02028284b7. - TensorFlow 2.0.0 - MacOS - Python 3.7.4 ### Reproduction To reproduce the issue, run ``` python doc/examples/parameter_server/async_parameter_server.py ``` This fails with ``` Traceback (most recent call last): File "doc/examples/parameter_server/async_parameter_server.py", line 9, in <module> import model File "/Users/rkn/anyscale/ray/doc/examples/parameter_server/model.py", line 12, in <module> from tensorflow.examples.tutorials.mnist import input_data ModuleNotFoundError: No module named 'tensorflow.examples.tutorials' ``` The same is true of `sync_parameter_server.py`. All of the examples under `doc/examples/` should be tested.
2019-12-30T03:03:57Z
[]
[]
Traceback (most recent call last): File "doc/examples/parameter_server/async_parameter_server.py", line 9, in <module> import model File "/Users/rkn/anyscale/ray/doc/examples/parameter_server/model.py", line 12, in <module> from tensorflow.examples.tutorials.mnist import input_data ModuleNotFoundError: No module named 'tensorflow.examples.tutorials'
17,901
ray-project/ray
ray-project__ray-6849
341ddd0a0909fcc755e3474427dda0b590fb19dd
diff --git a/python/ray/tune/suggest/variant_generator.py b/python/ray/tune/suggest/variant_generator.py --- a/python/ray/tune/suggest/variant_generator.py +++ b/python/ray/tune/suggest/variant_generator.py @@ -2,7 +2,6 @@ import logging import numpy import random -import types from ray.tune import TuneError from ray.tune.sample import sample_from @@ -126,7 +125,7 @@ def _generate_variants(spec): grid_vars = [] lambda_vars = [] for path, value in unresolved.items(): - if isinstance(value, types.FunctionType): + if callable(value): lambda_vars.append((path, value)) else: grid_vars.append((path, value))
[tune] Feature request: tune.sample_from does not support callable objects. ### System information - **OS Platform and Distribution (e.g., Linux Ubuntu 16.04)**: Linux Ubuntu 16.04 - **Ray installed from (source or binary)**: binary - **Ray version**: 0.7.2 - **Python version**: 3.2 - **Exact command to reproduce**: See below ### Describe the problem The `tune` sample_from interface is strictly limited to function objects, such as lambdas. This serves most use cases, but there are a number of instances where it's very useful to define a callable object to yield samples. (See trivial example below.) At the moment, providing a callable object returns errors from within tune variant generation, as the non-function-based `sample_from` entries are processed in grid entries. This can be resolved by changeing the sample/grid check from a direct check for `FunctionType` (Source location: https://github.com/ray-project/ray/blob/fadfa5f30bb654a74c781eaf8396a35af3ab7760/python/ray/tune/suggest/variant_generator.py#L116) to the builtin function `callable`. I'm not entirely clear if this is an intentional limitation, and changing this logic will likely require expansion of tune's tests and documentation to cover the new behavior. I would be happy to open a PR for this if a maintainer gives the feature a 👍. ### Source code / logs ```python import random import ray.tune as tune from ray.tune.suggest.variant_generator import generate_variants class Normal: def __call__(self, _config): return random.normalvariate(mu=0, sigma=1) grid_config = {"grid": tune.grid_search(list(range(2)))} sample_config = {"normal": tune.sample_from(Normal())} print(grid_config) print(list(generate_variants(grid_config))) print(sample_config) print(list(generate_variants(sample_config))) ``` Results: ``` {'grid': {'grid_search': [0, 1]}} [('grid=0', {'grid': 0}), ('grid=1', {'grid': 1})] {'normal': tune.sample_from(<__main__.Normal object at 0x7f08ed1d0f50>)} Traceback (most recent call last): File "sample_error.py", line 19, in <module> print(list(generate_variants(sample_config))) File "/work/home/lexaf/workspace/alphabeta/.conda/lib/python3.7/site-packages/ray/tune/suggest/variant_generator.py", line 43, in generate_variants for resolved_vars, spec in _generate_variants(unresolved_spec): File "/work/home/lexaf/workspace/alphabeta/.conda/lib/python3.7/site-packages/ray/tune/suggest/variant_generator.py", line 123, in _generate_variants for resolved_spec in grid_search: File "/work/home/lexaf/workspace/alphabeta/.conda/lib/python3.7/site-packages/ray/tune/suggest/variant_generator.py", line 193, in _grid_search_generator while value_indices[-1] < len(grid_vars[-1][1]): TypeError: object of type 'Normal' has no len() ```
@asford this would be great! I'd be more than happy to help shepherd this. I just had a case where this feature would've been useful.
2020-01-20T00:07:18Z
[]
[]
Traceback (most recent call last): File "sample_error.py", line 19, in <module> print(list(generate_variants(sample_config))) File "/work/home/lexaf/workspace/alphabeta/.conda/lib/python3.7/site-packages/ray/tune/suggest/variant_generator.py", line 43, in generate_variants for resolved_vars, spec in _generate_variants(unresolved_spec): File "/work/home/lexaf/workspace/alphabeta/.conda/lib/python3.7/site-packages/ray/tune/suggest/variant_generator.py", line 123, in _generate_variants for resolved_spec in grid_search: File "/work/home/lexaf/workspace/alphabeta/.conda/lib/python3.7/site-packages/ray/tune/suggest/variant_generator.py", line 193, in _grid_search_generator while value_indices[-1] < len(grid_vars[-1][1]): TypeError: object of type 'Normal' has no len()
17,905
ray-project/ray
ray-project__ray-7444
476b5c6196fa734794e395a53d2506e7c8485d12
diff --git a/rllib/agents/ars/ars.py b/rllib/agents/ars/ars.py --- a/rllib/agents/ars/ars.py +++ b/rllib/agents/ars/ars.py @@ -165,8 +165,7 @@ def _init(self, config, env_creator): # PyTorch check. if config["use_pytorch"]: raise ValueError( - "ARS does not support PyTorch yet! Use tf instead." - ) + "ARS does not support PyTorch yet! Use tf instead.") env = env_creator(config["env_config"]) from ray.rllib import models @@ -301,7 +300,7 @@ def _stop(self): w.__ray_terminate__.remote() @override(Trainer) - def compute_action(self, observation): + def compute_action(self, observation, *args, **kwargs): return self.policy.compute(observation, update=True)[0] def _collect_results(self, theta_id, min_episodes): diff --git a/rllib/agents/es/es.py b/rllib/agents/es/es.py --- a/rllib/agents/es/es.py +++ b/rllib/agents/es/es.py @@ -171,8 +171,7 @@ def _init(self, config, env_creator): # PyTorch check. if config["use_pytorch"]: raise ValueError( - "ES does not support PyTorch yet! Use tf instead." - ) + "ES does not support PyTorch yet! Use tf instead.") policy_params = {"action_noise_std": 0.01} @@ -292,7 +291,7 @@ def _train(self): return result @override(Trainer) - def compute_action(self, observation): + def compute_action(self, observation, *args, **kwargs): return self.policy.compute(observation, update=False)[0] @override(Trainer) diff --git a/rllib/rollout.py b/rllib/rollout.py --- a/rllib/rollout.py +++ b/rllib/rollout.py @@ -15,6 +15,7 @@ from ray.rllib.env import MultiAgentEnv from ray.rllib.env.base_env import _DUMMY_AGENT_ID from ray.rllib.evaluation.episode import _flatten_action +from ray.rllib.evaluation.worker_set import WorkerSet from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID from ray.rllib.utils.deprecation import deprecation_warning from ray.tune.utils import merge_dicts @@ -339,7 +340,7 @@ def rollout(agent, if saver is None: saver = RolloutSaver() - if hasattr(agent, "workers"): + if hasattr(agent, "workers") and isinstance(agent.workers, WorkerSet): env = agent.workers.local_worker().env multiagent = isinstance(env, MultiAgentEnv) if agent.workers.local_worker().multiagent: @@ -349,15 +350,22 @@ def rollout(agent, policy_map = agent.workers.local_worker().policy_map state_init = {p: m.get_initial_state() for p, m in policy_map.items()} use_lstm = {p: len(s) > 0 for p, s in state_init.items()} - action_init = { - p: _flatten_action(m.action_space.sample()) - for p, m in policy_map.items() - } else: env = gym.make(env_name) multiagent = False + try: + policy_map = {DEFAULT_POLICY_ID: agent.policy} + except AttributeError: + raise AttributeError( + "Agent ({}) does not have a `policy` property! This is needed " + "for performing (trained) agent rollouts.".format(agent)) use_lstm = {DEFAULT_POLICY_ID: False} + action_init = { + p: _flatten_action(m.action_space.sample()) + for p, m in policy_map.items() + } + # If monitoring has been requested, manually wrap our environment with a # gym monitor, which is set to record every episode. if video_dir:
[RLlib] Cannot rollout ES after training. Using ray 0.8.1. Having trained an agent with ES: ``` rllib train --run=ES --env=LunarLander-v2 --checkpoint-freq=10 ``` I can't play it. (It works with PPO). Executing this: ``` rllib rollout checkpoint_50/checkpoint-50 --run ES --env LunarLander-v2 --steps 600 ``` results in: ``` 2020-02-12 05:41:30,922 INFO trainable.py:423 -- Current state after restoring: {'_iteration': 50, '_timesteps_total': 16979666, '_time_total': 2578.4048051834106, '_episodes_total': None} Traceback (most recent call last): File "/home/andriy/miniconda3/envs/myproj/bin/rllib", line 8, in <module> sys.exit(cli()) File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/scripts.py", line 36, in cli rollout.run(options, rollout_parser) File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/rollout.py", line 265, in run args.no_render, args.monitor) File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/rollout.py", line 364, in rollout prev_action=prev_actions[agent_id], File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/rollout.py", line 272, in __missing__ self[key] = value = self.default_factory(key) File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/rollout.py", line 340, in <lambda> lambda agent_id: action_init[mapping_cache[agent_id]]) NameError: free variable 'action_init' referenced before assignment in enclosing scope ```
I'll take a look.
2020-03-04T10:20:33Z
[]
[]
Traceback (most recent call last): File "/home/andriy/miniconda3/envs/myproj/bin/rllib", line 8, in <module> sys.exit(cli()) File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/scripts.py", line 36, in cli rollout.run(options, rollout_parser) File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/rollout.py", line 265, in run args.no_render, args.monitor) File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/rollout.py", line 364, in rollout prev_action=prev_actions[agent_id], File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/rollout.py", line 272, in __missing__ self[key] = value = self.default_factory(key) File "/home/andriy/miniconda3/envs/myproj/lib/python3.7/site-packages/ray/rllib/rollout.py", line 340, in <lambda> lambda agent_id: action_init[mapping_cache[agent_id]]) NameError: free variable 'action_init' referenced before assignment in enclosing scope
17,933
ray-project/ray
ray-project__ray-7567
b38ed4be71d4be096f324c8c666e01e8af5f6c8b
diff --git a/python/ray/state.py b/python/ray/state.py --- a/python/ray/state.py +++ b/python/ray/state.py @@ -318,9 +318,9 @@ def _actor_table(self, actor_id): return {} gcs_entries = gcs_utils.GcsEntry.FromString(message) - assert len(gcs_entries.entries) == 1 + assert len(gcs_entries.entries) > 0 actor_table_data = gcs_utils.ActorTableData.FromString( - gcs_entries.entries[0]) + gcs_entries.entries[-1]) actor_info = { "ActorID": binary_to_hex(actor_table_data.actor_id),
[dashboard] dashboard.py crashes in example where actors are quickly created and go out of scope. ### What is the problem? I'm using - `ray==0.8.2` - Python 3.7.2 - MacOS ### Reproduction (REQUIRED) #### Bug 1 This is likely somewhat timing dependent, but when I run the following script ```python import ray ray.init() @ray.remote class GrandChild: def __init__(self): pass @ray.remote class Child: def __init__(self): grand_child_handle = GrandChild.remote() @ray.remote class Parent: def __init__(self): children_handles = [Child.remote() for _ in range(2)] parent_handle = Parent.remote() ``` the `dashboard.py` process crashes with the following error. ``` Traceback (most recent call last): File "/Users/rkn/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/rkn/opt/anaconda3/lib/python3.7/site-packages/ray/dashboard/dashboard.py", line 546, in run current_actor_table = ray.actors() File "/Users/rkn/opt/anaconda3/lib/python3.7/site-packages/ray/state.py", line 1133, in actors return state.actor_table(actor_id=actor_id) File "/Users/rkn/opt/anaconda3/lib/python3.7/site-packages/ray/state.py", line 369, in actor_table ray.ActorID(actor_id_binary)) File "/Users/rkn/opt/anaconda3/lib/python3.7/site-packages/ray/state.py", line 321, in _actor_table assert len(gcs_entries.entries) == 1 AssertionError ``` #### Bug 2 As a consequence, the dashboard doesn't display anything. There is a second bug here, which is that the error message wasn't pushed to the driver or displayed in the UI in any way. We have a test testing that tests that an error message is pushed to the driver when the monitor process dies. https://github.com/ray-project/ray/blob/007333b96006e090b14a415a8c5993d8b907f02a/python/ray/tests/test_failure.py#L544 I thought we had a similar test for the dashboard, but I don't see it anywhere. Note that we appear to have the plumbing in place to push error messages to the driver when the dashboard process dies, but I didn't see the relevant error message. See https://github.com/ray-project/ray/blob/f2faf8d26e489e0d879fd691abddeb3140c86bee/python/ray/dashboard/dashboard.py#L928-L929 cc @pcmoritz @simon-mo @mitchellstern
2020-03-11T21:36:29Z
[]
[]
Traceback (most recent call last): File "/Users/rkn/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/rkn/opt/anaconda3/lib/python3.7/site-packages/ray/dashboard/dashboard.py", line 546, in run current_actor_table = ray.actors() File "/Users/rkn/opt/anaconda3/lib/python3.7/site-packages/ray/state.py", line 1133, in actors return state.actor_table(actor_id=actor_id) File "/Users/rkn/opt/anaconda3/lib/python3.7/site-packages/ray/state.py", line 369, in actor_table ray.ActorID(actor_id_binary)) File "/Users/rkn/opt/anaconda3/lib/python3.7/site-packages/ray/state.py", line 321, in _actor_table assert len(gcs_entries.entries) == 1 AssertionError
17,935
ray-project/ray
ray-project__ray-7662
90b553ed058a546e036374cd0919e00604892514
diff --git a/rllib/policy/eager_tf_policy.py b/rllib/policy/eager_tf_policy.py --- a/rllib/policy/eager_tf_policy.py +++ b/rllib/policy/eager_tf_policy.py @@ -5,7 +5,6 @@ import logging import functools import numpy as np -import tree from ray.util.debug import log_once from ray.rllib.evaluation.episode import _flatten_action @@ -24,12 +23,12 @@ def _convert_to_tf(x): if isinstance(x, SampleBatch): x = {k: v for k, v in x.items() if k != SampleBatch.INFOS} - return tree.map_structure(_convert_to_tf, x) + return tf.nest.map_structure(_convert_to_tf, x) if isinstance(x, Policy): return x if x is not None: - x = tree.map_structure( + x = tf.nest.map_structure( lambda f: tf.convert_to_tensor(f) if f is not None else None, x) return x @@ -38,7 +37,7 @@ def _convert_to_numpy(x): if x is None: return None try: - return tree.map_structure(lambda component: component.numpy(), x) + return tf.nest.map_structure(lambda component: component.numpy(), x) except AttributeError: raise TypeError( ("Object of type {} has no method to convert to numpy.").format( @@ -66,7 +65,7 @@ def convert_eager_outputs(func): def _func(*args, **kwargs): out = func(*args, **kwargs) if tf.executing_eagerly(): - out = tree.map_structure(_convert_to_numpy, out) + out = tf.nest.map_structure(_convert_to_numpy, out) return out return _func @@ -551,7 +550,7 @@ def _initialize_loss_with_dummy_batch(self): SampleBatch.NEXT_OBS: np.array( [self.observation_space.sample()]), SampleBatch.DONES: np.array([False], dtype=np.bool), - SampleBatch.ACTIONS: tree.map_structure( + SampleBatch.ACTIONS: tf.nest.map_structure( lambda c: np.array([c]), self.action_space.sample()), SampleBatch.REWARDS: np.array([0], dtype=np.float32), } @@ -568,7 +567,8 @@ def _initialize_loss_with_dummy_batch(self): dummy_batch["seq_lens"] = np.array([1], dtype=np.int32) # Convert everything to tensors. - dummy_batch = tree.map_structure(tf.convert_to_tensor, dummy_batch) + dummy_batch = tf.nest.map_structure(tf.convert_to_tensor, + dummy_batch) # for IMPALA which expects a certain sample batch size. def tile_to(tensor, n): @@ -576,7 +576,7 @@ def tile_to(tensor, n): [n] + [1 for _ in tensor.shape.as_list()[1:]]) if get_batch_divisibility_req: - dummy_batch = tree.map_structure( + dummy_batch = tf.nest.map_structure( lambda c: tile_to(c, get_batch_divisibility_req(self)), dummy_batch) @@ -595,7 +595,7 @@ def tile_to(tensor, n): # overwrite any tensor state from that call) self.model.from_batch(dummy_batch) - postprocessed_batch = tree.map_structure( + postprocessed_batch = tf.nest.map_structure( lambda c: tf.convert_to_tensor(c), postprocessed_batch.data) loss_fn(self, self.model, self.dist_class, postprocessed_batch) diff --git a/rllib/policy/tf_policy.py b/rllib/policy/tf_policy.py --- a/rllib/policy/tf_policy.py +++ b/rllib/policy/tf_policy.py @@ -1,7 +1,6 @@ import errno import logging import os -import tree import numpy as np import ray @@ -212,10 +211,8 @@ def _initialize_loss(self, loss, loss_inputs): self._loss = loss self._optimizer = self.optimizer() - self._grads_and_vars = [ - (g, v) for (g, v) in self.gradients(self._optimizer, self._loss) - if g is not None - ] + self._grads_and_vars = [(g, v) for (g, v) in self.gradients( + self._optimizer, self._loss) if g is not None] self._grads = [g for (g, v) in self._grads_and_vars] # TODO(sven/ekl): Deprecate support for v1 models. @@ -493,7 +490,7 @@ def _build_signature_def(self): # build output signatures output_signature = self._extra_output_signature_def() - for i, a in enumerate(tree.flatten(self._sampled_action)): + for i, a in enumerate(tf.nest.flatten(self._sampled_action)): output_signature["actions_{}".format(i)] = \ tf.saved_model.utils.build_tensor_info(a) diff --git a/rllib/utils/torch_ops.py b/rllib/utils/torch_ops.py --- a/rllib/utils/torch_ops.py +++ b/rllib/utils/torch_ops.py @@ -1,9 +1,17 @@ -import tree +import logging from ray.rllib.utils.framework import try_import_torch torch, _ = try_import_torch() +logger = logging.getLogger(__name__) + +try: + import tree +except (ImportError, ModuleNotFoundError) as e: + logger.warning("`dm-tree` is not installed! Run `pip install dm-tree`.") + raise e + def sequence_mask(lengths, maxlen, dtype=None): """ @@ -34,6 +42,7 @@ def convert_to_non_torch_type(stats): dict: A new dict with the same structure as stats_dict, but with all values converted to non-torch Tensor types. """ + # The mapping function used to numpyize torch Tensors. def mapping(item): if isinstance(item, torch.Tensor):
[rllib] ModuleNotFoundError: No module named 'tree' *Ray version and other system information (Python version, TensorFlow version, OS):* Python3.6 pip install -U ray-0.9.0.dev0-cp36-cp36m-manylinux1_x86_64.whl On 2020-03-18 ### Reproduction (REQUIRED) $ rllib train -f atari-ddppo.yaml Traceback (most recent call last): File "/home/simon/anaconda3/bin/rllib", line 5, in <module> from ray.rllib.scripts import cli File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/__init__.py", line 9, in <module> from ray.rllib.evaluation.policy_graph import PolicyGraph File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/evaluation/__init__.py", line 2, in <module> from ray.rllib.evaluation.rollout_worker import RolloutWorker File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/evaluation/rollout_worker.py", line 19, in <module> from ray.rllib.evaluation.sampler import AsyncSampler, SyncSampler File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/evaluation/sampler.py", line 11, in <module> from ray.rllib.evaluation.sample_batch_builder import \ File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/evaluation/sample_batch_builder.py", line 6, in <module> from ray.rllib.policy.sample_batch import SampleBatch, MultiAgentBatch File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/policy/__init__.py", line 2, in <module> from ray.rllib.policy.torch_policy import TorchPolicy File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/policy/torch_policy.py", line 10, in <module> from ray.rllib.utils.torch_ops import convert_to_non_torch_type File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/utils/torch_ops.py", line 1, in <module> import tree ModuleNotFoundError: No module named 'tree'
2020-03-19T19:21:25Z
[]
[]
Traceback (most recent call last): File "/home/simon/anaconda3/bin/rllib", line 5, in <module> from ray.rllib.scripts import cli File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/__init__.py", line 9, in <module> from ray.rllib.evaluation.policy_graph import PolicyGraph File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/evaluation/__init__.py", line 2, in <module> from ray.rllib.evaluation.rollout_worker import RolloutWorker File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/evaluation/rollout_worker.py", line 19, in <module> from ray.rllib.evaluation.sampler import AsyncSampler, SyncSampler File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/evaluation/sampler.py", line 11, in <module> from ray.rllib.evaluation.sample_batch_builder import \ File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/evaluation/sample_batch_builder.py", line 6, in <module> from ray.rllib.policy.sample_batch import SampleBatch, MultiAgentBatch File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/policy/__init__.py", line 2, in <module> from ray.rllib.policy.torch_policy import TorchPolicy File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/policy/torch_policy.py", line 10, in <module> from ray.rllib.utils.torch_ops import convert_to_non_torch_type File "/home/simon/anaconda3/lib/python3.6/site-packages/ray/rllib/utils/torch_ops.py", line 1, in <module> import tree ModuleNotFoundError: No module named 'tree'
17,937
ray-project/ray
ray-project__ray-7752
ca6eabc9cb728a829d5305a4dd19216ed925f2e4
diff --git a/python/ray/worker.py b/python/ray/worker.py --- a/python/ray/worker.py +++ b/python/ray/worker.py @@ -1391,6 +1391,9 @@ def register_custom_serializer(cls, use_dict: Deprecated. class_id (str): Unique ID of the class. Autogenerated if None. """ + worker = global_worker + worker.check_connected() + if use_pickle: raise DeprecationWarning( "`use_pickle` is no longer a valid parameter and will be removed "
AttributeError: 'Worker' object has no attribute 'lock' the following code ```python import ray # ray.init() class Foo(object): def __init__(self, value): self.value = value def custom_serializer(obj): return obj.value def custom_deserializer(value): object = Foo(value) return object ray.register_custom_serializer( Foo, serializer=custom_serializer, deserializer=custom_deserializer) object_id = ray.put(Foo(100)) ``` trigger an exception when calling `ray.register_custom_serializer`, ``` Traceback (most recent call last): File "ray_err.py", line 20, in <module> Foo, serializer=custom_serializer, deserializer=custom_deserializer) File "/home/cloudhan/ray/python/ray/worker.py", line 1405, in register_custom_serializer context = global_worker.get_serialization_context() File "/home/cloudhan/ray/python/ray/worker.py", line 198, in get_serialization_context with self.lock: AttributeError: 'Worker' object has no attribute 'lock' ``` inspecting into the code you will find the lock is missing, https://github.com/ray-project/ray/blob/ca6eabc9cb728a829d5305a4dd19216ed925f2e4/python/ray/worker.py#L182-L202 the reason is simply not initialize ray, but the error is confusing.
2020-03-26T10:10:14Z
[]
[]
Traceback (most recent call last): File "ray_err.py", line 20, in <module> Foo, serializer=custom_serializer, deserializer=custom_deserializer) File "/home/cloudhan/ray/python/ray/worker.py", line 1405, in register_custom_serializer context = global_worker.get_serialization_context() File "/home/cloudhan/ray/python/ray/worker.py", line 198, in get_serialization_context with self.lock: AttributeError: 'Worker' object has no attribute 'lock'
17,943
ray-project/ray
ray-project__ray-7758
e196fcdbaf1a226e8f5ef5f28308f13d9be8261d
diff --git a/rllib/rollout.py b/rllib/rollout.py --- a/rllib/rollout.py +++ b/rllib/rollout.py @@ -11,7 +11,6 @@ import gym import ray -from ray.rllib.agents.registry import get_agent_class from ray.rllib.env import MultiAgentEnv from ray.rllib.env.base_env import _DUMMY_AGENT_ID from ray.rllib.evaluation.episode import _flatten_action @@ -19,6 +18,7 @@ from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID from ray.rllib.utils.deprecation import deprecation_warning from ray.tune.utils import merge_dicts +from ray.tune.registry import get_trainable_cls EXAMPLE_USAGE = """ Example Usage via RLlib CLI: @@ -274,7 +274,7 @@ def run(args, parser): ray.init() # Create the Trainer from config. - cls = get_agent_class(args.run) + cls = get_trainable_cls(args.run) agent = cls(env=args.env, config=config) # Load state from checkpoint. agent.restore(args.checkpoint)
[rllib] ray/rllib/rollout.py does not find registered trainables ### What is the problem? When using rollout.py with custom trainable (registered via `tune.register_trainable`) the script does not find the trainable. This seems to be caused because rollout.py uses `ray.rllib.agents.registry.get_agent_class` instead of `ray.tune.registry.get_trainable_cls`. *Ray version and other system information (Python version, TensorFlow version, OS):* python=3.7.3, ray[rllib,debug]==ray-0.9.0.dev0, tensorflow==1.15.0, Ubuntu 18.04 LTS ### Reproduction ``` #generate checkpoint rllib train --run DQN --env CartPole-v0 --stop '{"timesteps_total": 5000}' --checkpoint-freq 1 python rollout.py PATH_TO_CHECKPOINT --run OtherDQN --episodes 10 --out rollout.pkl 2020-03-26 16:28:25,858 INFO resource_spec.py:212 -- Starting Ray with 11.62 GiB memory available for workers and up to 5.83 GiB for objects. You can adjust these settings with ray.init(memory=<bytes>, object_store_memory=<bytes>). 2020-03-26 16:28:26,332 INFO services.py:1123 -- View the Ray dashboard at localhost:8265 Traceback (most recent call last): File "rollout.py", line 475, in <module> run(args, parser) File "rollout.py", line 285, in run cls = get_agent_class(args.run) File "/home/carl/miniconda3/envs/rollout_test/lib/python3.7/site-packages/ray/rllib/agents/registry.py", line 130, in get_agent_class return _get_agent_class(alg) File "/home/carl/miniconda3/envs/rollout_test/lib/python3.7/site-packages/ray/rllib/agents/registry.py", line 154, in _get_agent_class raise Exception(("Unknown algorithm {}.").format(alg)) Exception: Unknown algorithm OtherDQN. ``` The provided rollout.py adds the following lines at the start: ``` from ray.rllib.agents.dqn import DQNTrainer OtherDQNTrainer = DQNTrainer.with_updates( name="OtherDQN") ray.tune.register_trainable("OtherDQN", OtherDQNTrainer) ``` If `ray.rllib.agents.registry.get_agent_class` is replaces with `ray.tune.registry.get_trainable_cls` it works (with both "OtherDQN" and "DQN") [rollout.zip](https://github.com/ray-project/ray/files/4388161/rollout.zip) - [x] I have verified my script runs in a clean environment and reproduces the issue. - [x] I have verified the issue also occurs with the [latest wheels](https://ray.readthedocs.io/en/latest/installation.html).
2020-03-26T15:58:21Z
[]
[]
Traceback (most recent call last): File "rollout.py", line 475, in <module> run(args, parser) File "rollout.py", line 285, in run cls = get_agent_class(args.run) File "/home/carl/miniconda3/envs/rollout_test/lib/python3.7/site-packages/ray/rllib/agents/registry.py", line 130, in get_agent_class return _get_agent_class(alg) File "/home/carl/miniconda3/envs/rollout_test/lib/python3.7/site-packages/ray/rllib/agents/registry.py", line 154, in _get_agent_class raise Exception(("Unknown algorithm {}.").format(alg)) Exception: Unknown algorithm OtherDQN.
17,944
ray-project/ray
ray-project__ray-7877
7f9ddfcfd869b16b49e47f2d48c027d13dd45922
diff --git a/python/setup.py b/python/setup.py --- a/python/setup.py +++ b/python/setup.py @@ -191,7 +191,7 @@ def find_version(*filepath): # The BinaryDistribution argument triggers build_ext. distclass=BinaryDistribution, install_requires=requires, - setup_requires=["cython >= 0.29.14"], + setup_requires=["cython >= 0.29.14", "wheel"], extras_require=extras, entry_points={ "console_scripts": [
[ray] Build failure when installing from source <!--Please include [tune], [rllib], [autoscaler] etc. in the issue title if relevant--> ### What is the problem? I am trying to install ray from source. However, I receive the following error during the install process: ``` HEAD is now at 8ffe41c apply cpython patch bpo-39492 for the reference count issue + /usr/bin/python setup.py bdist_wheel usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' Traceback (most recent call last): File "setup.py", line 178, in <module> setup( File "/usr/lib/python3.8/site-packages/setuptools/__init__.py", line 144, in setup return distutils.core.setup(**attrs) File "/usr/lib/python3.8/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib/python3.8/distutils/dist.py", line 966, in run_commands self.run_command(cmd) File "/usr/lib/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "/usr/lib/python3.8/distutils/command/build.py", line 135, in run self.run_command(cmd_name) File "/usr/lib/python3.8/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/usr/lib/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "setup.py", line 107, in run subprocess.check_call(command) File "/usr/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['../build.sh', '-p', '/usr/bin/python']' returned non-zero exit status 1. ``` Note: `error invalid command 'bdist_wheel'` *Ray version and other system information (Python version, TensorFlow version, OS):* ray: 0.8.4 python: 3.8.2 os: Arch Linux ### Reproduction (REQUIRED) Please provide a script that can be run to reproduce the issue. The script should have **no external library dependencies** (i.e., use fake or mock data / environments): If we cannot run your script, we cannot fix your issue. - [ ] I have verified my script runs in a clean environment and reproduces the issue. - [ ] I have verified the issue also occurs with the [latest wheels](https://ray.readthedocs.io/en/latest/installation.html). The above does not apply since this is a build issue.
2020-04-02T21:56:48Z
[]
[]
Traceback (most recent call last): File "setup.py", line 178, in <module> setup( File "/usr/lib/python3.8/site-packages/setuptools/__init__.py", line 144, in setup return distutils.core.setup(**attrs) File "/usr/lib/python3.8/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib/python3.8/distutils/dist.py", line 966, in run_commands self.run_command(cmd) File "/usr/lib/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "/usr/lib/python3.8/distutils/command/build.py", line 135, in run self.run_command(cmd_name) File "/usr/lib/python3.8/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/usr/lib/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "setup.py", line 107, in run subprocess.check_call(command) File "/usr/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['../build.sh', '-p', '/usr/bin/python']' returned non-zero exit status 1.
17,951
ray-project/ray
ray-project__ray-8012
e68d601ec74369bb2ca9fbda80f5361d2483afcf
diff --git a/python/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist.py b/python/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist.py --- a/python/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist.py +++ b/python/ray/tune/examples/pbt_dcgan_mnist/pbt_dcgan_mnist.py @@ -49,6 +49,8 @@ # iterations of actual training in each Trainable _train train_iterations_per_step = 5 +MODEL_PATH = os.path.expanduser("~/.ray/models/mnist_cnn.pt") + def get_data_loader(): dataset = dset.MNIST( @@ -305,6 +307,16 @@ def _export_model(self, export_formats, export_dir): args, _ = parser.parse_known_args() ray.init() + import urllib.request + # Download a pre-trained MNIST model for inception score calculation. + # This is a tiny model (<100kb). + if not os.path.exists(MODEL_PATH): + print("downloading model") + os.makedirs(os.path.dirname(MODEL_PATH), exist_ok=True) + urllib.request.urlretrieve( + "https://github.com/ray-project/ray/raw/master/python/ray/tune/" + "examples/pbt_dcgan_mnist/mnist_cnn.pt", MODEL_PATH) + dataloader = get_data_loader() if not args.smoke_test: # Plot some training images @@ -322,10 +334,7 @@ def _export_model(self, export_formats, export_dir): # load the pretrained mnist classification model for inception_score mnist_cnn = Net() - model_path = os.path.join( - os.path.dirname(ray.__file__), - "tune/examples/pbt_dcgan_mnist/mnist_cnn.pt") - mnist_cnn.load_state_dict(torch.load(model_path)) + mnist_cnn.load_state_dict(torch.load(MODEL_PATH)) mnist_cnn.eval() mnist_model_ref = ray.put(mnist_cnn) diff --git a/python/ray/util/sgd/torch/examples/__init__.py b/python/ray/util/sgd/torch/examples/__init__.py new file mode 100644 diff --git a/python/ray/util/sgd/torch/examples/benchmarks/benchmark.py b/python/ray/util/sgd/torch/examples/benchmarks/benchmark.py --- a/python/ray/util/sgd/torch/examples/benchmarks/benchmark.py +++ b/python/ray/util/sgd/torch/examples/benchmarks/benchmark.py @@ -16,6 +16,8 @@ parser = argparse.ArgumentParser( description="PyTorch Synthetic Benchmark", formatter_class=argparse.ArgumentDefaultsHelpFormatter) +parser.add_argument( + "--smoke-test", action="store_true", default=False, help="finish quickly.") parser.add_argument( "--fp16", action="store_true", default=False, help="use fp16 training") @@ -49,6 +51,16 @@ help="Disables cluster training") args = parser.parse_args() + +if args.smoke_test: + args.model = "resnet18" + args.batch_size = 1 + args.num_iters = 1 + args.num_batches_per_iter = 2 + args.num_warmup_batches = 2 + args.local = True + args.no_cuda = True + args.cuda = not args.no_cuda and torch.cuda.is_available() device = "GPU" if args.cuda else "CPU" @@ -68,7 +80,6 @@ def setup(self, config): self.data, self.target = data, target def train_epoch(self, *pargs, **kwargs): - # print(self.model) def benchmark(): self.optimizer.zero_grad() output = self.model(self.data) @@ -76,11 +87,11 @@ def benchmark(): loss.backward() self.optimizer.step() - # print("Running warmup...") + print("Running warmup...") if self.global_step == 0: timeit.timeit(benchmark, number=args.num_warmup_batches) self.global_step += 1 - # print("Running benchmark...") + print("Running benchmark...") time = timeit.timeit(benchmark, number=args.num_batches_per_iter) img_sec = args.batch_size * args.num_batches_per_iter / time return {"img_sec": img_sec} @@ -99,7 +110,7 @@ def benchmark(): model_creator=lambda cfg: getattr(models, args.model)(), optimizer_creator=lambda model, cfg: optim.SGD( model.parameters(), lr=0.01 * cfg.get("lr_scaler")), - data_creator=lambda cfg: LinearDataset(4, 2), + data_creator=lambda cfg: LinearDataset(4, 2), # Mock dataset. initialization_hook=init_hook, config=dict( lr_scaler=num_workers), diff --git a/python/ray/util/sgd/torch/examples/dcgan.py b/python/ray/util/sgd/torch/examples/dcgan.py --- a/python/ray/util/sgd/torch/examples/dcgan.py +++ b/python/ray/util/sgd/torch/examples/dcgan.py @@ -21,6 +21,8 @@ from ray.util.sgd.utils import override from ray.util.sgd.torch import TrainingOperator +MODEL_PATH = os.path.expanduser("~/.ray/models/mnist_cnn.pt") + def data_creator(config): dataset = datasets.MNIST( @@ -227,9 +229,7 @@ def train_example(num_workers=1, use_gpu=False, test_mode=False): config = { "test_mode": test_mode, "batch_size": 16 if test_mode else 512 // num_workers, - "classification_model_path": os.path.join( - os.path.dirname(ray.__file__), - "util/sgd/torch/examples/mnist_cnn.pt") + "classification_model_path": MODEL_PATH } trainer = TorchTrainer( model_creator=model_creator, @@ -256,6 +256,16 @@ def train_example(num_workers=1, use_gpu=False, test_mode=False): if __name__ == "__main__": + import urllib.request + # Download a pre-trained MNIST model for inception score calculation. + # This is a tiny model (<100kb). + if not os.path.exists(MODEL_PATH): + print("downloading model") + os.makedirs(os.path.dirname(MODEL_PATH), exist_ok=True) + urllib.request.urlretrieve( + "https://github.com/ray-project/ray/raw/master/python/ray/tune/" + "examples/pbt_dcgan_mnist/mnist_cnn.pt", MODEL_PATH) + parser = argparse.ArgumentParser() parser.add_argument( "--smoke-test", action="store_true", help="Finish quickly for testing")
[sgd] dcgan.py needs a better reference to mnist_cnn.pt <!--Please include [tune], [rllib], [autoscaler] etc. in the issue title if relevant--> ### What is the problem? `dcgan.py` sample identifies classification model path as following: ``` "classification_model_path": os.path.join( os.path.dirname(ray.__file__), "util/sgd/torch/examples/mnist_cnn.pt") ``` But Ray doesn't have samples in the package. In case I just want to run the sample using pre-installed ray from pip, I got the following error: ``` $ python dcgan.py --num-workers 44 2020-04-13 16:32:44,305 INFO resource_spec.py:204 -- Starting Ray with 120.21 GiB memory available for workers and up to 55.52 GiB for objects. You can adjust these settings with ray.init(me mory=<bytes>, object_store_memory=<bytes>). 2020-04-13 16:32:44,732 INFO services.py:1146 -- View the Ray dashboard at localhost:8265 Traceback (most recent call last): File "dcgan.py", line 283, in <module> trainer = train_example( File "dcgan.py", line 236, in train_example trainer = TorchTrainer( File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/torch_trainer.py", line 233, in __init__ self._start_workers(self.max_replicas) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/torch_trainer.py", line 320, in _start_workers self.local_worker.setup(address, 0, num_workers) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/distributed_torch_runner.py", line 46, in setup self._setup_training() File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/distributed_torch_runner.py", line 92, in _setup_training self.training_operator = self.training_operator_cls( File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/training_operator.py", line 96, in __init__ self.setup(config) File "dcgan.py", line 136, in setup torch.load(config["classification_model_path"])) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 525, in load with _open_file_like(f, 'rb') as opened_file: File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 212, in _open_file_like return _open_file(name_or_buffer, mode) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 193, in __init__ super(_open_file, self).__init__(open(name, mode)) FileNotFoundError: [Errno 2] No such file or directory: '/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/examples/mnist_cnn.pt' 2020-04-13 16:32:49,606 ERROR worker.py:1011 -- Possible unhandled error from worker: ray::DistributedTorchRunner.setup() (pid=67029, ip=10.125.21.189) File "python/ray/_raylet.pyx", line 452, in ray._raylet.execute_task File "python/ray/_raylet.pyx", line 407, in ray._raylet.execute_task.function_executor File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/distributed_torch_runner.py", line 46, in setup self._setup_training() File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/distributed_torch_runner.py", line 92, in _setup_training self.training_operator = self.training_operator_cls( File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/training_operator.py", line 96, in __init__ self.setup(config) File "dcgan.py", line 136, in setup torch.load(config["classification_model_path"])) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 525, in load with _open_file_like(f, 'rb') as opened_file: File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 212, in _open_file_like return _open_file(name_or_buffer, mode) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 193, in __init__ super(_open_file, self).__init__(open(name, mode)) FileNotFoundError: [Errno 2] No such file or directory: '/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/examples/mnist_cnn.pt' ``` *Ray version and other system information (Python version, TensorFlow version, OS):* ray 0.8.4, Ubuntu 18.04, Torch 1.4.0 ### Reproduction (REQUIRED) Please provide a script that can be run to reproduce the issue. The script should have **no external library dependencies** (i.e., use fake or mock data / environments): `python dcgan.py` from `./ray/python/ray/util/sgd/torch/examples` directory of the repo If we cannot run your script, we cannot fix your issue. - [x] I have verified my script runs in a clean environment and reproduces the issue. - [x] I have verified the issue also occurs with the [latest wheels](https://ray.readthedocs.io/en/latest/installation.html).
@PovelikinRostislav Thanks for opening this issue! The solution to this is just to download it from Git rather than packaging it with Ray. I can get to this later this week, but feel free to push a PR!
2020-04-13T22:36:54Z
[]
[]
Traceback (most recent call last): File "dcgan.py", line 283, in <module> trainer = train_example( File "dcgan.py", line 236, in train_example trainer = TorchTrainer( File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/torch_trainer.py", line 233, in __init__ self._start_workers(self.max_replicas) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/torch_trainer.py", line 320, in _start_workers self.local_worker.setup(address, 0, num_workers) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/distributed_torch_runner.py", line 46, in setup self._setup_training() File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/distributed_torch_runner.py", line 92, in _setup_training self.training_operator = self.training_operator_cls( File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/training_operator.py", line 96, in __init__ self.setup(config) File "dcgan.py", line 136, in setup torch.load(config["classification_model_path"])) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 525, in load with _open_file_like(f, 'rb') as opened_file: File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 212, in _open_file_like return _open_file(name_or_buffer, mode) File "/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/torch/serialization.py", line 193, in __init__ super(_open_file, self).__init__(open(name, mode)) FileNotFoundError: [Errno 2] No such file or directory: '/rpovelik/installed/miniconda3/envs/ray/lib/python3.8/site-packages/ray/util/sgd/torch/examples/mnist_cnn.pt'
17,954
ray-project/ray
ray-project__ray-8628
cd5a207d69cdaf05b47d956c18e89d928585eec7
diff --git a/python/ray/node.py b/python/ray/node.py --- a/python/ray/node.py +++ b/python/ray/node.py @@ -4,6 +4,7 @@ import errno import os import logging +import random import signal import socket import subprocess @@ -24,6 +25,7 @@ logger = logging.getLogger(__name__) SESSION_LATEST = "session_latest" +NUMBER_OF_PORT_RETRIES = 40 class Node: @@ -167,7 +169,8 @@ def __init__(self, # NOTE: There is a possible but unlikely race condition where # the port is bound by another process between now and when the # raylet starts. - self._ray_params.node_manager_port = self._get_unused_port() + self._ray_params.node_manager_port, self._socket = \ + self._get_unused_port(close_on_exit=False) if not connect_only and spawn_reaper and not self.kernel_fate_share: self.start_reaper_process() @@ -300,6 +303,14 @@ def node_manager_port(self): """Get the node manager's port.""" return self._ray_params.node_manager_port + @property + def socket(self): + """Get the socket reserving the node manager's port""" + try: + return self._socket + except AttributeError: + return None + @property def address_info(self): """Get a dictionary of addresses.""" @@ -395,12 +406,30 @@ def new_log_files(self, name): log_stderr_file = open(log_stderr, "a", buffering=1) return log_stdout_file, log_stderr_file - def _get_unused_port(self): + def _get_unused_port(self, close_on_exit=True): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) port = s.getsockname()[1] - s.close() - return port + + # Try to generate a port that is far above the 'next available' one. + # This solves issue #8254 where GRPC fails because the port assigned + # from this method has been used by a different process. + for _ in range(NUMBER_OF_PORT_RETRIES): + new_port = random.randint(port, 65535) + new_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + new_s.bind(("", new_port)) + except OSError: + new_s.close() + continue + s.close() + if close_on_exit: + new_s.close() + return new_port, new_s + logger.error("Unable to succeed in selecting a random port.") + if close_on_exit: + s.close() + return port, s def _prepare_socket_file(self, socket_path, default_prefix): """Prepare the socket file for raylet and plasma. @@ -417,7 +446,7 @@ def _prepare_socket_file(self, socket_path, default_prefix): if sys.platform == "win32": if socket_path is None: result = "tcp://{}:{}".format(self._localhost, - self._get_unused_port()) + self._get_unused_port()[0]) else: if socket_path is None: result = self._make_inc_temp( @@ -598,7 +627,8 @@ def start_raylet(self, use_valgrind=False, use_profiler=False): include_java=self._ray_params.include_java, java_worker_options=self._ray_params.java_worker_options, load_code_from_local=self._ray_params.load_code_from_local, - fate_share=self.kernel_fate_share) + fate_share=self.kernel_fate_share, + socket_to_use=self.socket) assert ray_constants.PROCESS_TYPE_RAYLET not in self.all_processes self.all_processes[ray_constants.PROCESS_TYPE_RAYLET] = [process_info] diff --git a/python/ray/services.py b/python/ray/services.py --- a/python/ray/services.py +++ b/python/ray/services.py @@ -1230,7 +1230,8 @@ def start_raylet(redis_address, include_java=False, java_worker_options=None, load_code_from_local=False, - fate_share=None): + fate_share=None, + socket_to_use=None): """Start a raylet, which is a combined local scheduler and object manager. Args: @@ -1361,6 +1362,8 @@ def start_raylet(redis_address, "--temp_dir={}".format(temp_dir), "--session_dir={}".format(session_dir), ] + if socket_to_use: + socket_to_use.close() process_info = start_ray_process( command, ray_constants.PROCESS_TYPE_RAYLET,
[Core] Node Failure Long Running Test Failed at `grpc::ServerInterface::RegisteredAsyncRequest::IssueRequest()` <!--Please include [tune], [rllib], [autoscaler] etc. in the issue title if relevant--> ### What is the problem? Node Failure Long Running test fails with the error log below. ``` (pid=raylet) E0429 02:32:06.263886 22036 process.cc:274] Failed to wait for process 22047 with error system:10: No child processes E0429 02:32:12.346844 23272 task_manager.cc:288] 3 retries left for task b48f33dc1265b526ffffffff0100, attempting to resubmit. E0429 02:32:12.346899 23272 core_worker.cc:373] Will resubmit task after a 5000ms delay: Type=NORMAL_TASK, Language=PYTHON, function_descriptor={type=PythonFunctionDescriptor, module_name=__main__, class_name=, function_name=f, function_hash=7d2c6c88e5e801d48a350076f2117e717fe12224}, task_id=b48f33dc1265b526ffffffff0100, job_id=0100, num_args=2, num_returns=1 (pid=raylet) E0429 02:32:12.347446 22089 process.cc:274] Failed to wait for process 22100 with error system:10: No child processes 2020-04-29 02:32:12,653 INFO resource_spec.py:212 -- Starting Ray with 27.88 GiB memory available for workers and up to 0.15 GiB for objects. You can adjust these settings with ray.init(memory=<bytes>, object_store_memory=<bytes>). (pid=raylet) E0429 02:32:12.732946757 22142 server_chttp2.cc:40] {"created":"@1588127532.732848116","description":"No address added out of total 1 resolved","file":"external/com_github_grpc_grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc","file_line":394,"referenced_errors":[{"created":"@1588127532.732846227","description":"Failed to add any wildcard listeners","file":"external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_server_posix.cc","file_line":341,"referenced_errors":[{"created":"@1588127532.732832876","description":"Unable to configure socket","fd":44,"file":"external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc","file_line":208,"referenced_errors":[{"created":"@1588127532.732823689","description":"Address already in use","errno":98,"file":"external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc","file_line":181,"os_error":"Address already in use","syscall":"bind"}]},{"created":"@1588127532.732845812","description":"Unable to configure socket","fd":44,"file":"external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc","file_line":208,"referenced_errors":[{"created":"@1588127532.732843382","description":"Address already in use","errno":98,"file":"external/com_github_grpc_grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc","file_line":181,"os_error":"Address already in use","syscall":"bind"}]}]}]} (pid=raylet) *** Aborted at 1588127532 (unix time) try "date -d @1588127532" if you are using GNU date *** (pid=raylet) PC: @ 0x0 (unknown) (pid=raylet) *** SIGSEGV (@0x58) received by PID 22142 (TID 0x7fc3a66d37c0) from PID 88; stack trace: *** (pid=raylet) @ 0x7fc3a5c32390 (unknown) (pid=raylet) @ 0x5596e3957692 grpc::ServerInterface::RegisteredAsyncRequest::IssueRequest() (pid=raylet) @ 0x5596e35b2149 ray::rpc::NodeManagerService::WithAsyncMethod_RequestWorkerLease<>::RequestRequestWorkerLease() (pid=raylet) @ 0x5596e35c7b1b ray::rpc::ServerCallFactoryImpl<>::CreateCall() (pid=raylet) @ 0x5596e380bfe1 ray::rpc::GrpcServer::Run() (pid=raylet) @ 0x5596e3629acc ray::raylet::NodeManager::NodeManager() (pid=raylet) @ 0x5596e35cbc07 ray::raylet::Raylet::Raylet() (pid=raylet) @ 0x5596e359848d main (pid=raylet) @ 0x7fc3a5459830 __libc_start_main (pid=raylet) @ 0x5596e35a9391 (unknown) (pid=22153) E0429 02:32:13.864451 22153 raylet_client.cc:69] Retrying to connect to socket for pathname /tmp/ray/session_2020-04-28_20-19-44_770473_22870/sockets/raylet.8 (num_attempts = 1, num_retries = 5) (pid=22153) E0429 02:32:14.364712 22153 raylet_client.cc:69] Retrying to connect to socket for pathname /tmp/ray/session_2020-04-28_20-19-44_770473_22870/sockets/raylet.8 (num_attempts = 2, num_retries = 5) (pid=22153) E0429 02:32:14.864863 22153 raylet_client.cc:69] Retrying to connect to socket for pathname /tmp/ray/session_2020-04-28_20-19-44_770473_22870/sockets/raylet.8 (num_attempts = 3, num_retries = 5) (pid=22153) E0429 02:32:15.365000 22153 raylet_client.cc:69] Retrying to connect to socket for pathname /tmp/ray/session_2020-04-28_20-19-44_770473_22870/sockets/raylet.8 (num_attempts = 4, num_retries = 5) (pid=22153) F0429 02:32:15.865115 22153 raylet_client.cc:78] Could not connect to socket /tmp/ray/session_2020-04-28_20-19-44_770473_22870/sockets/raylet.8 (pid=22153) *** Check failure stack trace: *** (pid=22153) @ 0x7f5d3b2b40ed google::LogMessage::Fail() (pid=22153) @ 0x7f5d3b2b555c google::LogMessage::SendToLog() (pid=22153) @ 0x7f5d3b2b3dc9 google::LogMessage::Flush() (pid=22153) @ 0x7f5d3b2b3fe1 google::LogMessage::~LogMessage() (pid=22153) @ 0x7f5d3b03bb39 ray::RayLog::~RayLog() (pid=22153) @ 0x7f5d3ae55133 ray::raylet::RayletConnection::RayletConnection() (pid=22153) @ 0x7f5d3ae55abf ray::raylet::RayletClient::RayletClient() (pid=22153) @ 0x7f5d3adf513b ray::CoreWorker::CoreWorker() (pid=22153) @ 0x7f5d3adf8984 ray::CoreWorkerProcess::CreateWorker() (pid=22153) @ 0x7f5d3adf8efb ray::CoreWorkerProcess::CoreWorkerProcess() (pid=22153) @ 0x7f5d3adf93fb ray::CoreWorkerProcess::Initialize() (pid=22153) @ 0x7f5d3ad6c06c __pyx_pw_3ray_7_raylet_10CoreWorker_1__cinit__() (pid=22153) @ 0x7f5d3ad6d155 __pyx_tp_new_3ray_7_raylet_CoreWorker() (pid=22153) @ 0x55db24e47965 type_call (pid=22153) @ 0x55db24db7d7b _PyObject_FastCallDict (pid=22153) @ 0x55db24e477ce call_function (pid=22153) @ 0x55db24e69cba _PyEval_EvalFrameDefault (pid=22153) @ 0x55db24e40dae _PyEval_EvalCodeWithName (pid=22153) @ 0x55db24e41941 fast_function (pid=22153) @ 0x55db24e47755 call_function (pid=22153) @ 0x55db24e6aa7a _PyEval_EvalFrameDefault (pid=22153) @ 0x55db24e42459 PyEval_EvalCodeEx (pid=22153) @ 0x55db24e431ec PyEval_EvalCode (pid=22153) @ 0x55db24ebd9a4 run_mod (pid=22153) @ 0x55db24ebdda1 PyRun_FileExFlags (pid=22153) @ 0x55db24ebdfa4 PyRun_SimpleFileExFlags (pid=22153) @ 0x55db24ec1a9e Py_Main (pid=22153) @ 0x55db24d894be main (pid=22153) @ 0x7f5d3cd85830 __libc_start_main (pid=22153) @ 0x55db24e70773 (unknown) Traceback (most recent call last): File "workloads/node_failures.py", line 57, in <module> cluster.add_node() File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/ray/cluster_utils.py", line 115, in add_node self._wait_for_node(node) File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/ray/cluster_utils.py", line 165, in _wait_for_node raise TimeoutError("Timed out while waiting for nodes to join.") TimeoutError: Timed out while waiting for nodes to join. (pid=raylet) E0429 02:32:42.965368 13125 process.cc:274] Failed to wait for process 13136 with error system:10: No child processes (pid=raylet) E0429 02:32:43.045863 1167 process.cc:274] Failed to wait for process 1178 with error system:10: No child processes 2020-04-29 02:32:43,942 ERROR import_thread.py:93 -- ImportThread: Connection closed by server. 2020-04-29 02:32:43,942 ERROR worker.py:996 -- print_logs: Connection closed by server. 2020-04-29 02:32:43,942 ERROR worker.py:1096 -- listen_error_messages_raylet: Connection closed by server. E0429 02:32:45.999132 22870 raylet_client.cc:90] IOError: [RayletClient] Connection closed unexpectedly. [RayletClient] Failed to disconnect from raylet. ``` *Ray version and other system information (Python version, TensorFlow version, OS):* ### Reproduction (REQUIRED) This is hard to reproduce, but it happens consistently in multiple long running tests. For the logs above, it happens after 2909 iterations. - [ ] I have verified my script runs in a clean environment and reproduces the issue. - [ ] I have verified the issue also occurs with the [latest wheels](https://docs.ray.io/en/latest/installation.html).
@stephanie-wang Are you working on this issue? I don't think this is a P0. It's just a side effect of rapidly killing and adding ray nodes on the same machine. Raylet gRPC server cannot bind to a port that's just released by killing ray node. This is uncommon in production scenarios. Moving it to P1. However, we do need to fix the long running test by adding some sleep buffer between killing and adding a new node, maybe inside test_reconstruction as well. It looks like the ultimate source of the problem is that the port for GPRC is selected before GRPC actually uses that port: https://github.com/ray-project/ray/blob/137519e19d77debb5427a24279320f21e805867f/python/ray/node.py#L167 @simon-mo What are your thoughts on this? One possible fix is to randomize the port instead of using kernel to get unused port. This can avoid possible race condition. The reason is that current `_get_unused_port` procedure returns unused port in sequence and is likely to duplicate port numbers, since we close the socket immediately and release the ownership of that port. ```python def _get_unused_port(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", 0)) port = s.getsockname()[1] # fix: add some random integer to the port number, returns if available, else retry s.close() return port ```
2020-05-27T01:18:16Z
[]
[]
Traceback (most recent call last): File "workloads/node_failures.py", line 57, in <module> cluster.add_node() File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/ray/cluster_utils.py", line 115, in add_node self._wait_for_node(node) File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/ray/cluster_utils.py", line 165, in _wait_for_node raise TimeoutError("Timed out while waiting for nodes to join.") TimeoutError: Timed out while waiting for nodes to join.
17,979
ray-project/ray
ray-project__ray-8840
3b32cf14a7aa9bdf3053646d63bc5cd1311d7d77
diff --git a/python/ray/autoscaler/autoscaler.py b/python/ray/autoscaler/autoscaler.py --- a/python/ray/autoscaler/autoscaler.py +++ b/python/ray/autoscaler/autoscaler.py @@ -321,7 +321,8 @@ def recover_if_needed(self, node_id, now): self.config["worker_start_ray_commands"]), runtime_hash=self.runtime_hash, process_runner=self.process_runner, - use_internal_ip=True) + use_internal_ip=True, + docker_config=self.config["docker"]) updater.start() self.updaters[node_id] = updater @@ -360,7 +361,8 @@ def spawn_updater(self, node_id, init_commands, ray_start_commands): ray_start_commands=with_head_node_ip(ray_start_commands), runtime_hash=self.runtime_hash, process_runner=self.process_runner, - use_internal_ip=True) + use_internal_ip=True, + docker_config=self.config["docker"]) updater.start() self.updaters[node_id] = updater diff --git a/python/ray/autoscaler/commands.py b/python/ray/autoscaler/commands.py --- a/python/ray/autoscaler/commands.py +++ b/python/ray/autoscaler/commands.py @@ -147,7 +147,8 @@ def kill_node(config_file, yes, hard, override_cluster_name): initialization_commands=[], setup_commands=[], ray_start_commands=[], - runtime_hash="") + runtime_hash="", + docker_config=config["docker"]) _exec(updater, "ray stop", False, False) @@ -286,7 +287,7 @@ def get_or_create_head_node(config, config_file, no_restart, restart_only, yes, setup_commands=init_commands, ray_start_commands=ray_start_commands, runtime_hash=runtime_hash, - ) + docker_config=config["docker"]) updater.start() updater.join() @@ -407,7 +408,7 @@ def exec_cluster(config_file, setup_commands=[], ray_start_commands=[], runtime_hash="", - ) + docker_config=config["docker"]) def wrap_docker(command): container_name = config["docker"]["container_name"] @@ -529,7 +530,7 @@ def rsync(config_file, setup_commands=[], ray_start_commands=[], runtime_hash="", - ) + docker_config=config["docker"]) if down: rsync = updater.rsync_down else: diff --git a/python/ray/autoscaler/docker.py b/python/ray/autoscaler/docker.py --- a/python/ray/autoscaler/docker.py +++ b/python/ray/autoscaler/docker.py @@ -80,6 +80,10 @@ def aptwait_cmd(): "do echo 'Waiting for release of dpkg/apt locks'; sleep 5; done") +def check_docker_running_cmd(cname): + return " ".join(["docker", "inspect", "-f", "'{{.State.Running}}'", cname]) + + def docker_start_cmds(user, image, mount, cname, user_options): cmds = [] @@ -99,15 +103,13 @@ def docker_start_cmds(user, image, mount, cname, user_options): user_options_str = " ".join(user_options) # docker run command - docker_check = [ - "docker", "inspect", "-f", "'{{.State.Running}}'", cname, "||" - ] + docker_check = check_docker_running_cmd(cname) + " || " docker_run = [ "docker", "run", "--rm", "--name {}".format(cname), "-d", "-it", port_flags, mount_flags, env_flags, user_options_str, "--net=host", image, "bash" ] - cmds.append(" ".join(docker_check + docker_run)) + cmds.append(docker_check + " ".join(docker_run)) return cmds diff --git a/python/ray/autoscaler/kubernetes/node_provider.py b/python/ray/autoscaler/kubernetes/node_provider.py --- a/python/ray/autoscaler/kubernetes/node_provider.py +++ b/python/ray/autoscaler/kubernetes/node_provider.py @@ -87,7 +87,13 @@ def terminate_nodes(self, node_ids): for node_id in node_ids: self.terminate_node(node_id) - def get_command_runner(self, log_prefix, node_id, auth_config, - cluster_name, process_runner, use_internal_ip): + def get_command_runner(self, + log_prefix, + node_id, + auth_config, + cluster_name, + process_runner, + use_internal_ip, + docker_config=None): return KubernetesCommandRunner(log_prefix, self.namespace, node_id, auth_config, process_runner) diff --git a/python/ray/autoscaler/node_provider.py b/python/ray/autoscaler/node_provider.py --- a/python/ray/autoscaler/node_provider.py +++ b/python/ray/autoscaler/node_provider.py @@ -3,7 +3,7 @@ import os import yaml -from ray.autoscaler.updater import SSHCommandRunner +from ray.autoscaler.updater import SSHCommandRunner, DockerCommandRunner logger = logging.getLogger(__name__) @@ -211,8 +211,14 @@ def cleanup(self): """Clean-up when a Provider is no longer required.""" pass - def get_command_runner(self, log_prefix, node_id, auth_config, - cluster_name, process_runner, use_internal_ip): + def get_command_runner(self, + log_prefix, + node_id, + auth_config, + cluster_name, + process_runner, + use_internal_ip, + docker_config=None): """ Returns the CommandRunner class used to perform SSH commands. Args: @@ -226,7 +232,19 @@ def get_command_runner(self, log_prefix, node_id, auth_config, in the CommandRunner. E.g., subprocess. use_internal_ip(bool): whether the node_id belongs to an internal ip or external ip. + docker_config(dict): If set, the docker information of the docker + container that commands should be run on. """ - - return SSHCommandRunner(log_prefix, node_id, self, auth_config, - cluster_name, process_runner, use_internal_ip) + common_args = { + "log_prefix": log_prefix, + "node_id": node_id, + "provider": self, + "auth_config": auth_config, + "cluster_name": cluster_name, + "process_runner": process_runner, + "use_internal_ip": use_internal_ip + } + if docker_config and docker_config["container_name"] != "": + return DockerCommandRunner(docker_config, **common_args) + else: + return SSHCommandRunner(**common_args) diff --git a/python/ray/autoscaler/updater.py b/python/ray/autoscaler/updater.py --- a/python/ray/autoscaler/updater.py +++ b/python/ray/autoscaler/updater.py @@ -17,6 +17,7 @@ STATUS_UP_TO_DATE, STATUS_UPDATE_FAILED, STATUS_WAITING_FOR_SSH, \ STATUS_SETTING_UP, STATUS_SYNCING_FILES from ray.autoscaler.log_timer import LogTimer +from ray.autoscaler.docker import check_docker_running_cmd logger = logging.getLogger(__name__) @@ -294,6 +295,66 @@ def remote_shell_command_str(self): self.ssh_private_key, self.ssh_user, self.ssh_ip) +class DockerCommandRunner(SSHCommandRunner): + def __init__(self, docker_config, **common_args): + self.ssh_command_runner = SSHCommandRunner(**common_args) + self.docker_name = docker_config["container_name"] + self.docker_config = docker_config + self.home_dir = None + + def run(self, + cmd, + timeout=120, + exit_on_fail=False, + port_forward=None, + with_output=False): + + return self.ssh_command_runner.run( + cmd, + timeout=timeout, + exit_on_fail=exit_on_fail, + port_forward=None, + with_output=False) + + def check_container_status(self): + no_exist = "not_present" + cmd = check_docker_running_cmd(self.docker_name) + " ".join( + ["||", "echo", quote(no_exist)]) + output = self.ssh_command_runner.run( + cmd, with_output=True).decode("utf-8").strip() + if no_exist in output: + return False + return output + + def run_rsync_up(self, source, target): + self.ssh_command_runner.run_rsync_up(source, target) + if self.check_container_status(): + self.ssh_command_runner.run("docker cp {} {}:{}".format( + target, self.docker_name, self.docker_expand_user(target))) + + def run_rsync_down(self, source, target): + self.ssh_command_runner.run("docker cp {}:{} {}".format( + self.docker_name, self.docker_expand_user(source), source)) + self.ssh_command_runner.run_rsync_down(source, target) + + def remote_shell_command_str(self): + inner_str = self.ssh_command_runner.remote_shell_command_str().replace( + "ssh", "ssh -tt", 1).strip("\n") + return inner_str + " docker exec -it {} /bin/bash\n".format( + self.docker_name) + + def docker_expand_user(self, string): + if string.find("~") == 0: + if self.home_dir is None: + self.home_dir = self.ssh_command_runner.run( + "docker exec {} env | grep HOME | cut -d'=' -f2".format( + self.docker_name), + with_output=True).decode("utf-8").strip() + return string.replace("~", self.home_dir) + else: + return string + + class NodeUpdater: """A process for syncing files and running init commands on a node.""" @@ -309,14 +370,15 @@ def __init__(self, ray_start_commands, runtime_hash, process_runner=subprocess, - use_internal_ip=False): + use_internal_ip=False, + docker_config=None): self.log_prefix = "NodeUpdater: {}: ".format(node_id) use_internal_ip = (use_internal_ip or provider_config.get("use_internal_ips", False)) self.cmd_runner = provider.get_command_runner( self.log_prefix, node_id, auth_config, cluster_name, - process_runner, use_internal_ip) + process_runner, use_internal_ip, docker_config) self.daemon = True self.process_runner = process_runner diff --git a/python/ray/scripts/scripts.py b/python/ray/scripts/scripts.py --- a/python/ray/scripts/scripts.py +++ b/python/ray/scripts/scripts.py @@ -833,8 +833,9 @@ def submit(cluster_config_file, docker, screen, tmux, stop, start, if start: create_or_update_cluster(cluster_config_file, None, None, False, False, True, cluster_name) - - target = os.path.join("~", os.path.basename(script)) + target = os.path.basename(script) + if not docker: + target = os.path.join("~", target) rsync(cluster_config_file, script, target, cluster_name, down=False) command_parts = ["python", target]
Docker + AWS hanging at "Set tag..." for autoscaler ### What is the problem? Using latest version of Ray (0.9.0.dev0) ### Reproduction (REQUIRED) If we take the example AWS configuration YAML, given [here](https://docs.ray.io/en/master/autoscaling.html?highlight=docker) (under AWS header) and simply change line 26 and 27 to use an actual Docker image: [example_full.zip](https://github.com/ray-project/ray/files/4744002/example_full.zip) Running any commands with the autoscaler hangs and eventually fails: ``` ray up config/example_full.yaml 2020-06-08 01:13:10,526 INFO config.py:143 -- _configure_iam_role: Role not specified for head node, using arn:aws:iam::<redacted>:instance-profile/ray-autoscaler-v1 2020-06-08 01:13:11,089 INFO config.py:194 -- _configure_key_pair: KeyName not specified for nodes, using ray-autoscaler_us-west-2 2020-06-08 01:13:11,365 INFO config.py:235 -- _configure_subnet: SubnetIds not specified for head node, using [('subnet-<redacted>', 'us-west-2b'), ('subnet-<redacted>', 'us-west-2a')] 2020-06-08 01:13:11,366 INFO config.py:241 -- _configure_subnet: SubnetId not specified for workers, using [('subnet-<redacted>', 'us-west-2b'), ('subnet-<redacted>', 'us-west-2a')] 2020-06-08 01:13:11,725 INFO config.py:261 -- _configure_security_group: SecurityGroupIds not specified for head node, using ray-autoscaler-default (sg-<redacted>) 2020-06-08 01:13:11,725 INFO config.py:268 -- _configure_security_group: SecurityGroupIds not specified for workers, using ray-autoscaler-default (sg-<redacted>) This will restart cluster services [y/N]: y 2020-06-08 01:13:15,214 INFO commands.py:238 -- get_or_create_head_node: Updating files on head node... 2020-06-08 01:13:15,215 INFO updater.py:379 -- NodeUpdater: i-<redacted>: Updating to <redacted> 2020-06-08 01:13:15,216 INFO updater.py:423 -- NodeUpdater: i-<redacted>: Waiting for remote shell... 2020-06-08 01:13:15,422 INFO log_timer.py:22 -- AWSNodeProvider: Set tag ray-node-status=waiting-for-ssh on ['i-<redacted> Exception in thread Thread-2: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/home/richard/improbable/ray/python/ray/autoscaler/updater.py", line 383, in run self.do_update() File "/home/richard/improbable/ray/python/ray/autoscaler/updater.py", line 450, in do_update self.wait_ready(deadline) File "/home/richard/improbable/ray/python/ray/autoscaler/updater.py", line 444, in wait_ready assert False, "Unable to connect to node" AssertionError: Unable to connect to node 2020-06-08 01:11:59,679 ERROR commands.py:304 -- get_or_create_head_node: Updating <redacted> failed 2020-06-08 01:11:59,701 INFO log_timer.py:22 -- AWSNodeProvider: Set tag ray-node-status=update-failed on ['i-<redacted>'] [LogTimer=333ms] ``` If I remove the Docker image and name on line 26 and line 27, the YAML file **succeeds** for any ray up / attach / submit etc. command. (Related, it would be nice if we piped out more verbose error messages about why errors like this occur when using the autoscaler.) - [X] I have verified my script runs in a clean environment and reproduces the issue. - [X] I have verified the issue also occurs with the [latest wheels](https://docs.ray.io/en/latest/installation.html).
2020-06-08T18:57:27Z
[]
[]
Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/home/richard/improbable/ray/python/ray/autoscaler/updater.py", line 383, in run self.do_update() File "/home/richard/improbable/ray/python/ray/autoscaler/updater.py", line 450, in do_update self.wait_ready(deadline) File "/home/richard/improbable/ray/python/ray/autoscaler/updater.py", line 444, in wait_ready assert False, "Unable to connect to node" AssertionError: Unable to connect to node
17,988
ray-project/ray
ray-project__ray-8842
3388864768fa198f27496824407f9aee16256c2f
diff --git a/python/ray/async_compat.py b/python/ray/async_compat.py --- a/python/ray/async_compat.py +++ b/python/ray/async_compat.py @@ -75,6 +75,11 @@ def done_callback(future): # Result from direct call. assert isinstance(result, AsyncGetResponse), result if result.plasma_fallback_id is None: + # If this future has result set already, we just need to + # skip the set result/exception procedure. + if user_future.done(): + return + if isinstance(result.result, ray.exceptions.RayTaskError): ray.worker.last_task_error_raise_time = time.time() user_future.set_exception(
[Asyncio] InvalidStateError when multiple awaits on same oid <!--Please include [tune], [rllib], [autoscaler] etc. in the issue title if relevant--> ### What is the problem? *Ray version and other system information (Python version, TensorFlow version, OS):* ### Reproduction (REQUIRED) Please provide a script that can be run to reproduce the issue. The script should have **no external library dependencies** (i.e., use fake or mock data / environments): If we cannot run your script, we cannot fix your issue. ```python import ray import time ray.init() @ray.remote def f(): time.sleep(5) oid = f.remote() await asyncio.wait_for(oid, timeout=1) await asyncio.wait_for(oid, timeout=1) ``` Output ``` Exception in callback get_async.<locals>.done_callback(<Future finis... result=None)>) at /Users/simonmo/Desktop/ray/ray/python/ray/async_compat.py:65 handle: <Handle get_async.<locals>.done_callback(<Future finis... result=None)>) at /Users/simonmo/Desktop/ray/ray/python/ray/async_compat.py:65> Traceback (most recent call last): File "/Users/simonmo/miniconda3/lib/python3.6/asyncio/events.py", line 145, in _run self._callback(*self._args) File "/Users/simonmo/Desktop/ray/ray/python/ray/async_compat.py", line 83, in done_callback user_future.set_result(result.result) asyncio.base_futures.InvalidStateError: invalid state ``` - [ ] I have verified my script runs in a clean environment and reproduces the issue. - [ ] I have verified the issue also occurs with the [latest wheels](https://docs.ray.io/en/latest/installation.html).
Oh nice. This must be related to @allenyin55 's issue right?
2020-06-08T20:06:07Z
[]
[]
Traceback (most recent call last): File "/Users/simonmo/miniconda3/lib/python3.6/asyncio/events.py", line 145, in _run self._callback(*self._args) File "/Users/simonmo/Desktop/ray/ray/python/ray/async_compat.py", line 83, in done_callback user_future.set_result(result.result) asyncio.base_futures.InvalidStateError: invalid state
17,989
ray-project/ray
ray-project__ray-9517
2f674728a683ec7d466917afc6327308f2483ec1
diff --git a/python/ray/tune/checkpoint_manager.py b/python/ray/tune/checkpoint_manager.py --- a/python/ray/tune/checkpoint_manager.py +++ b/python/ray/tune/checkpoint_manager.py @@ -109,6 +109,10 @@ def on_checkpoint(self, checkpoint): return old_checkpoint = self.newest_persistent_checkpoint + + if old_checkpoint.value == checkpoint.value: + return + self.newest_persistent_checkpoint = checkpoint # Remove the old checkpoint if it isn't one of the best ones.
[tune] Population-based training: broken when using keep_checkpoint_num When using **population-based** training TUNE stops after some times throwing the following error: `There are paused trials, but no more pending trials with sufficient resources.` This is caused by not finding the latest checkpoint: ``` Failure # 1 (occurred at 2020-06-19_11-26-36) Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/ray/tune/ray_trial_executor.py", line 294, in start_trial self._start_trial(trial, checkpoint, train=train) File "/usr/local/lib/python3.6/dist-packages/ray/tune/ray_trial_executor.py", line 235, in _start_trial self.restore(trial, checkpoint) File "/usr/local/lib/python3.6/dist-packages/ray/tune/ray_trial_executor.py", line 673, in restore data_dict = TrainableUtil.pickle_checkpoint(value) File "/usr/local/lib/python3.6/dist-packages/ray/tune/trainable.py", line 62, in pickle_checkpoint checkpoint_dir = TrainableUtil.find_checkpoint_dir(checkpoint_path) File "/usr/local/lib/python3.6/dist-packages/ray/tune/trainable.py", line 87, in find_checkpoint_dir raise FileNotFoundError("Path does not exist", checkpoint_path) FileNotFoundError: [Errno Path does not exist] /content/TRASH_TUNE_PBT_oversampling_mimic_densenet121/TUNE_Model_0_2020-06-19_11-24-215xncry9c/checkpoint_6/ ``` The error appears to be somewhat random since it only appears after quite some iterations The error can be reproduced in this [colab notebook](https://colab.research.google.com/drive/1-o896bEUm7DTvS24Do0btlqbSHre49MH?usp=sharing). **It is not a COLAB related issue since the same problem arises on our own server.** @richardliaw Is this related to #8772 ?
Yeah this seems like an issue. We'll take a look into this. This is the issue (just for reference): ``` from ray.tune.schedulers import PopulationBasedTraining scheduler = PopulationBasedTraining( time_attr='training_iteration', metric='mean_accuracy', mode='max', perturbation_interval=1, log_config=True, hyperparam_mutations={ "lr": lambda: 10 ** np.random.uniform(-2, -5) }) train_config = {'lr': 0.01} analysis = tune.run( TUNE_Model, # Reference to the model class. config=train_config, fail_fast=True, # Stop after first error num_samples=4, # Num of different hyperparameter configurations search_alg=None, # Search algotihm like Hyperopt, Nevergrad... resources_per_trial={"gpu": 1}, # Requested resources per TRIAL. If set to fraction, total_GPUS/res_p_trial can be run in parallel global_checkpoint_period=np.inf, # Do not save checkpoints based on time interval checkpoint_freq = 1, # Save checkpoint every time the checkpoint_score_attr improves checkpoint_at_end = True, keep_checkpoints_num = 2, # Keep only the best checkpoint checkpoint_score_attr = 'mean_accuracy', # Metric used to compare checkpoints verbose=1, scheduler=scheduler, # Stop bad trials early name="TRASH_TUNE_PBT_oversampling_mimic_densenet121", local_dir="/content", stop={ # Stop a single trial if one of the conditions are met "mean_accuracy": 0.85, "training_iteration": 15}) ``` @Cryptiex for a temporary workaround, I think you can just do: ```python def _save(self, tmp_checkpoint_dir): """ Saves the model checkpoint depending of checkpoint_freq and checkpoint_at_end set in tune.run. Arguments: tmp_checkpoint_dir {str} -- [Folder where the checkpoints get saved.] Returns: [str] -- [tmp_checkpoint_dir] """ checkpoint_path = os.path.join(tmp_checkpoint_dir, "model.pth") torch.save(self.model.state_dict(), checkpoint_path) return checkpoint_path # CHANGE THIS def _restore(self, checkpoint_path): # CHANGE THIS """ Restore model. """ self.model.load_state_dict(torch.load(checkpoint_path)) I think the temporary fix actually is to comment this out: ``` keep_checkpoints_num = 2, # Keep only the best checkpoint ``` Thanks for the fast reply! Commenting out **keep_checkpoints_num** worked for me as a temporary fix. Any idea where this is coming from? Does the PBT scheduler reference an already deleted checkpoint? Yeah, I think it's something about not properly bookkeeping the checkpoints on disk. Any updates on this? The temporary fix seems not to work as indicated by #8441 and my own experiences
2020-07-16T09:16:32Z
[]
[]
Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/ray/tune/ray_trial_executor.py", line 294, in start_trial self._start_trial(trial, checkpoint, train=train) File "/usr/local/lib/python3.6/dist-packages/ray/tune/ray_trial_executor.py", line 235, in _start_trial self.restore(trial, checkpoint) File "/usr/local/lib/python3.6/dist-packages/ray/tune/ray_trial_executor.py", line 673, in restore data_dict = TrainableUtil.pickle_checkpoint(value) File "/usr/local/lib/python3.6/dist-packages/ray/tune/trainable.py", line 62, in pickle_checkpoint checkpoint_dir = TrainableUtil.find_checkpoint_dir(checkpoint_path) File "/usr/local/lib/python3.6/dist-packages/ray/tune/trainable.py", line 87, in find_checkpoint_dir raise FileNotFoundError("Path does not exist", checkpoint_path) FileNotFoundError: [Errno Path does not exist] /content/TRASH_TUNE_PBT_oversampling_mimic_densenet121/TUNE_Model_0_2020-06-19_11-24-215xncry9c/checkpoint_6/
18,015
scipy/scipy
scipy__scipy-3314
0da153ee00778abfb2ce621796625b4d929b85e9
diff --git a/scipy/io/mmio.py b/scipy/io/mmio.py --- a/scipy/io/mmio.py +++ b/scipy/io/mmio.py @@ -12,6 +12,7 @@ from __future__ import division, print_function, absolute_import import os +import sys from numpy import asarray, real, imag, conj, zeros, ndarray, concatenate, \ ones, ascontiguousarray, vstack, savetxt, fromfile, fromstring from numpy.compat import asbytes, asstr @@ -451,9 +452,15 @@ def _parse_body(self, stream): return coo_matrix((rows, cols), dtype=dtype) try: + # passing a gzipped file to fromfile/fromstring doesn't work + # with Python3 + if (sys.version_info >= (3, 0) and + isinstance(stream, (gzip.GzipFile, bz2.BZ2File))): + flat_data = fromstring(stream.read(), sep=' ') # fromfile works for normal files - flat_data = fromfile(stream, sep=' ') - except: + else: + flat_data = fromfile(stream, sep=' ') + except Exception: # fallback - fromfile fails for some file-like objects flat_data = fromstring(stream.read(), sep=' ')
Fix mmio/fromfile on gzip on Python 3 (Trac #1627) _Original ticket http://projects.scipy.org/scipy/ticket/1627 on 2012-03-22 by @pv, assigned to unknown._ Consider this: ``` Python 3.2.2 >>> from scipy.io import mmread >>> mmread('illc1033.mtx.gz') Traceback (most recent call last): ... File ".../scipy/io/mmio.py", line 447, in _parse_body flat_data = flat_data.reshape(-1,3) ValueError: total size of new array must be unchanged ``` with ftp://math.nist.gov/pub/MatrixMarket2/Harwell-Boeing/lsq/illc1033.mtx.gz The reason is passing a GzipFile handle to `numpy.fromfile`. On Python 3, PyObject_AsFileDescriptor in `fromfile` succeeds on a GzipFile, although it should fail (there is no OS level file handle giving the uncompressed stream). As a consequence, the `fromfile` call in `mmread` apparently ends up reading an compressed data stream, which causes this error. This should be worked around in `scipy.io.mmio` until Python 3 (and Numpy) are fixed.
I just tried this, and `np.fromfile` does work on the gzip handle: ``` $ python3 Python 3.2.5 (default, Oct 29 2013, 10:03:36) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> import gzip >>> G = gzip.open("illc1033.mtx.gz", "r") >>> np.fromfile(G) array([ 1.02866359e-064, 1.50168922e-076, 1.31490163e+294, ..., 1.15488103e+120, 1.31512507e+171, 6.63818119e-221]) >>> >>> from scipy.io import mmread >>> mmread("illc1033.mtx.gz") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python3.2/site-packages/scipy/io/mmio.py", line 73, in mmread return MMFile().read(source) File "/usr/lib64/python3.2/site-packages/scipy/io/mmio.py", line 326, in read return self._parse_body(stream) File "/usr/lib64/python3.2/site-packages/scipy/io/mmio.py", line 475, in _parse_body flat_data = flat_data.reshape(-1,3) ValueError: total size of new array must be unchanged ``` Did I understand you wrong, @pv? This is on scipy 0.13.0. `np.fromfile` reads the data from the raw stream and not the uncompressed one, so it doesn't work. The numbers you get from fromfile are garbage.
2014-02-12T12:05:57Z
[]
[]
Traceback (most recent call last): ... File ".../scipy/io/mmio.py", line 447, in _parse_body
18,054