D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
proc
/
self
/
root
/
proc
/
thread-self
/
root
/
home
/
vblioqus
/
karachi777.vip
/
in
/
106014
/
900508
/
Filename :
lib.tar
back
Copy
python3.3/site-packages/pip/log.py 0000644 00000022357 15154344632 0012774 0 ustar 00 """Logging """ import sys import os import logging from pip import backwardcompat from pip._vendor import colorama, pkg_resources def _color_wrap(*colors): def wrapped(inp): return "".join(list(colors) + [inp, colorama.Style.RESET_ALL]) return wrapped def should_color(consumer, environ, std=(sys.stdout, sys.stderr)): real_consumer = (consumer if not isinstance(consumer, colorama.AnsiToWin32) else consumer.wrapped) # If consumer isn't stdout or stderr we shouldn't colorize it if real_consumer not in std: return False # If consumer is a tty we should color it if hasattr(real_consumer, "isatty") and real_consumer.isatty(): return True # If we have an ASNI term we should color it if environ.get("TERM") == "ANSI": return True # If anything else we should not color it return False def should_warn(current_version, removal_version): # Our Significant digits on versions is 2, so remove everything but the # first two places. current_version = ".".join(current_version.split(".")[:2]) removal_version = ".".join(removal_version.split(".")[:2]) # Our warning threshold is one minor version before removal, so we # decrement the minor version by one major, minor = removal_version.split(".") minor = str(int(minor) - 1) warn_version = ".".join([major, minor]) # Test if our current_version should be a warn return (pkg_resources.parse_version(current_version) < pkg_resources.parse_version(warn_version)) class Logger(object): """ Logging object for use in command-line script. Allows ranges of levels, to avoid some redundancy of displayed information. """ VERBOSE_DEBUG = logging.DEBUG - 1 DEBUG = logging.DEBUG INFO = logging.INFO NOTIFY = (logging.INFO + logging.WARN) / 2 WARN = WARNING = logging.WARN ERROR = logging.ERROR FATAL = logging.FATAL LEVELS = [VERBOSE_DEBUG, DEBUG, INFO, NOTIFY, WARN, ERROR, FATAL] COLORS = { WARN: _color_wrap(colorama.Fore.YELLOW), ERROR: _color_wrap(colorama.Fore.RED), FATAL: _color_wrap(colorama.Fore.RED), } def __init__(self): self.consumers = [] self.indent = 0 self.explicit_levels = False self.in_progress = None self.in_progress_hanging = False def add_consumers(self, *consumers): if sys.platform.startswith("win"): for level, consumer in consumers: if hasattr(consumer, "write"): self.consumers.append( (level, colorama.AnsiToWin32(consumer)), ) else: self.consumers.append((level, consumer)) else: self.consumers.extend(consumers) def debug(self, msg, *args, **kw): self.log(self.DEBUG, msg, *args, **kw) def info(self, msg, *args, **kw): self.log(self.INFO, msg, *args, **kw) def notify(self, msg, *args, **kw): self.log(self.NOTIFY, msg, *args, **kw) def warn(self, msg, *args, **kw): self.log(self.WARN, msg, *args, **kw) def error(self, msg, *args, **kw): self.log(self.ERROR, msg, *args, **kw) def fatal(self, msg, *args, **kw): self.log(self.FATAL, msg, *args, **kw) def deprecated(self, removal_version, msg, *args, **kwargs): """ Logs deprecation message which is log level WARN if the ``removal_version`` is > 1 minor release away and log level ERROR otherwise. removal_version should be the version that the deprecated feature is expected to be removed in, so something that will not exist in version 1.7, but will in 1.6 would have a removal_version of 1.7. """ from pip import __version__ if should_warn(__version__, removal_version): self.warn(msg, *args, **kwargs) else: self.error(msg, *args, **kwargs) def log(self, level, msg, *args, **kw): if args: if kw: raise TypeError( "You may give positional or keyword arguments, not both") args = args or kw # render if args: rendered = msg % args else: rendered = msg rendered = ' ' * self.indent + rendered if self.explicit_levels: ## FIXME: should this be a name, not a level number? rendered = '%02i %s' % (level, rendered) for consumer_level, consumer in self.consumers: if self.level_matches(level, consumer_level): if (self.in_progress_hanging and consumer in (sys.stdout, sys.stderr)): self.in_progress_hanging = False sys.stdout.write('\n') sys.stdout.flush() if hasattr(consumer, 'write'): write_content = rendered + '\n' if should_color(consumer, os.environ): # We are printing to stdout or stderr and it supports # colors so render our text colored colorizer = self.COLORS.get(level, lambda x: x) write_content = colorizer(write_content) consumer.write(write_content) if hasattr(consumer, 'flush'): consumer.flush() else: consumer(rendered) def _show_progress(self): """Should we display download progress?""" return (self.stdout_level_matches(self.NOTIFY) and sys.stdout.isatty()) def start_progress(self, msg): assert not self.in_progress, ( "Tried to start_progress(%r) while in_progress %r" % (msg, self.in_progress)) if self._show_progress(): sys.stdout.write(' ' * self.indent + msg) sys.stdout.flush() self.in_progress_hanging = True else: self.in_progress_hanging = False self.in_progress = msg self.last_message = None def end_progress(self, msg='done.'): assert self.in_progress, ( "Tried to end_progress without start_progress") if self._show_progress(): if not self.in_progress_hanging: # Some message has been printed out since start_progress sys.stdout.write('...' + self.in_progress + msg + '\n') sys.stdout.flush() else: # These erase any messages shown with show_progress (besides .'s) logger.show_progress('') logger.show_progress('') sys.stdout.write(msg + '\n') sys.stdout.flush() self.in_progress = None self.in_progress_hanging = False def show_progress(self, message=None): """If we are in a progress scope, and no log messages have been shown, write out another '.'""" if self.in_progress_hanging: if message is None: sys.stdout.write('.') sys.stdout.flush() else: if self.last_message: padding = ' ' * max(0, len(self.last_message) - len(message)) else: padding = '' sys.stdout.write('\r%s%s%s%s' % (' ' * self.indent, self.in_progress, message, padding)) sys.stdout.flush() self.last_message = message def stdout_level_matches(self, level): """Returns true if a message at this level will go to stdout""" return self.level_matches(level, self._stdout_level()) def _stdout_level(self): """Returns the level that stdout runs at""" for level, consumer in self.consumers: if consumer is sys.stdout: return level return self.FATAL def level_matches(self, level, consumer_level): """ >>> l = Logger() >>> l.level_matches(3, 4) False >>> l.level_matches(3, 2) True >>> l.level_matches(slice(None, 3), 3) False >>> l.level_matches(slice(None, 3), 2) True >>> l.level_matches(slice(1, 3), 1) True >>> l.level_matches(slice(2, 3), 1) False """ if isinstance(level, slice): start, stop = level.start, level.stop if start is not None and start > consumer_level: return False if stop is not None or stop <= consumer_level: return False return True else: return level >= consumer_level @classmethod def level_for_integer(cls, level): levels = cls.LEVELS if level < 0: return levels[0] if level >= len(levels): return levels[-1] return levels[level] def move_stdout_to_stderr(self): to_remove = [] to_add = [] for consumer_level, consumer in self.consumers: if consumer == sys.stdout: to_remove.append((consumer_level, consumer)) to_add.append((consumer_level, sys.stderr)) for item in to_remove: self.consumers.remove(item) self.consumers.extend(to_add) logger = Logger() python3.3/site-packages/pip/locations.py 0000644 00000014072 15154344632 0014201 0 ustar 00 """Locations where we look for configs, install stuff, etc""" import sys import site import os import tempfile from distutils.command.install import install, SCHEME_KEYS import getpass from pip.backwardcompat import get_python_lib, get_path_uid, user_site import pip.exceptions DELETE_MARKER_MESSAGE = '''\ This file is placed here by pip to indicate the source was put here by pip. Once this package is successfully installed this source code will be deleted (unless you remove this file). ''' PIP_DELETE_MARKER_FILENAME = 'pip-delete-this-directory.txt' def write_delete_marker_file(directory): """ Write the pip delete marker file into this directory. """ filepath = os.path.join(directory, PIP_DELETE_MARKER_FILENAME) marker_fp = open(filepath, 'w') marker_fp.write(DELETE_MARKER_MESSAGE) marker_fp.close() def running_under_virtualenv(): """ Return True if we're running inside a virtualenv, False otherwise. """ if hasattr(sys, 'real_prefix'): return True elif sys.prefix != getattr(sys, "base_prefix", sys.prefix): return True return False def virtualenv_no_global(): """ Return True if in a venv and no system site packages. """ #this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file site_mod_dir = os.path.dirname(os.path.abspath(site.__file__)) no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt') if running_under_virtualenv() and os.path.isfile(no_global_file): return True def __get_username(): """ Returns the effective username of the current process. """ if sys.platform == 'win32': return getpass.getuser() import pwd return pwd.getpwuid(os.geteuid()).pw_name def _get_build_prefix(): """ Returns a safe build_prefix """ path = os.path.join(tempfile.gettempdir(), 'pip_build_%s' % __get_username()) if sys.platform == 'win32': """ on windows(tested on 7) temp dirs are isolated """ return path try: os.mkdir(path) write_delete_marker_file(path) except OSError: file_uid = None try: # raises OSError for symlinks # https://github.com/pypa/pip/pull/935#discussion_r5307003 file_uid = get_path_uid(path) except OSError: file_uid = None if file_uid != os.geteuid(): msg = "The temporary folder for building (%s) is either not owned by you, or is a symlink." \ % path print (msg) print("pip will not work until the temporary folder is " + \ "either deleted or is a real directory owned by your user account.") raise pip.exceptions.InstallationError(msg) return path if running_under_virtualenv(): build_prefix = os.path.join(sys.prefix, 'build') src_prefix = os.path.join(sys.prefix, 'src') else: # Note: intentionally NOT using mkdtemp # See https://github.com/pypa/pip/issues/906 for plan to move to mkdtemp build_prefix = _get_build_prefix() ## FIXME: keep src in cwd for now (it is not a temporary folder) try: src_prefix = os.path.join(os.getcwd(), 'src') except OSError: # In case the current working directory has been renamed or deleted sys.exit("The folder you are executing pip from can no longer be found.") # under Mac OS X + virtualenv sys.prefix is not properly resolved # it is something like /path/to/python/bin/.. # Note: using realpath due to tmp dirs on OSX being symlinks build_prefix = os.path.abspath(os.path.realpath(build_prefix)) src_prefix = os.path.abspath(src_prefix) # FIXME doesn't account for venv linked to global site-packages site_packages = get_python_lib() user_dir = os.path.expanduser('~') if sys.platform == 'win32': bin_py = os.path.join(sys.prefix, 'Scripts') bin_user = os.path.join(user_site, 'Scripts') if user_site else None # buildout uses 'bin' on Windows too? if not os.path.exists(bin_py): bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') if user_site else None default_storage_dir = os.path.join(user_dir, 'pip') default_config_file = os.path.join(default_storage_dir, 'pip.ini') default_log_file = os.path.join(default_storage_dir, 'pip.log') else: bin_py = os.path.join(sys.prefix, 'bin') bin_user = os.path.join(user_site, 'bin') if user_site else None default_storage_dir = os.path.join(user_dir, '.pip') default_config_file = os.path.join(default_storage_dir, 'pip.conf') default_log_file = os.path.join(default_storage_dir, 'pip.log') # Forcing to use /usr/local/bin for standard Mac OS X framework installs # Also log to ~/Library/Logs/ for use with the Console.app log viewer if sys.platform[:6] == 'darwin' and sys.prefix[:16] == '/System/Library/': bin_py = '/usr/local/bin' default_log_file = os.path.join(user_dir, 'Library/Logs/pip.log') def distutils_scheme(dist_name, user=False, home=None, root=None): """ Return a distutils install scheme """ from distutils.dist import Distribution scheme = {} d = Distribution({'name': dist_name}) d.parse_config_files() i = d.get_command_obj('install', create=True) # NOTE: setting user or home has the side-effect of creating the home dir or # user base for installations during finalize_options() # ideally, we'd prefer a scheme class that has no side-effects. i.user = user or i.user i.home = home or i.home i.root = root or i.root i.finalize_options() for key in SCHEME_KEYS: scheme[key] = getattr(i, 'install_'+key) if running_under_virtualenv(): scheme['headers'] = os.path.join(sys.prefix, 'include', 'site', 'python' + sys.version[:3], dist_name) if root is not None: scheme["headers"] = os.path.join( root, os.path.abspath(scheme["headers"])[1:], ) return scheme python3.3/site-packages/pip/pep425tags.py 0000644 00000005631 15154344632 0014105 0 ustar 00 """Generate and work with PEP 425 Compatibility Tags.""" import sys import warnings try: import sysconfig except ImportError: # pragma nocover # Python < 2.7 import distutils.sysconfig as sysconfig import distutils.util def get_abbr_impl(): """Return abbreviated implementation name.""" if hasattr(sys, 'pypy_version_info'): pyimpl = 'pp' elif sys.platform.startswith('java'): pyimpl = 'jy' elif sys.platform == 'cli': pyimpl = 'ip' else: pyimpl = 'cp' return pyimpl def get_impl_ver(): """Return implementation version.""" return ''.join(map(str, sys.version_info[:2])) def get_platform(): """Return our platform name 'win32', 'linux_x86_64'""" # XXX remove distutils dependency return distutils.util.get_platform().replace('.', '_').replace('-', '_') def get_supported(versions=None, noarch=False): """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. """ supported = [] # Versions must be given with respect to the preference if versions is None: versions = [] major = sys.version_info[0] # Support all previous minor Python versions. for minor in range(sys.version_info[1], -1, -1): versions.append(''.join(map(str, (major, minor)))) impl = get_abbr_impl() abis = [] try: soabi = sysconfig.get_config_var('SOABI') except IOError as e: # Issue #1074 warnings.warn("{0}".format(e), RuntimeWarning) soabi = None if soabi and soabi.startswith('cpython-'): abis[0:0] = ['cp' + soabi.split('-', 1)[-1]] abi3s = set() import imp for suffix in imp.get_suffixes(): if suffix[0].startswith('.abi'): abi3s.add(suffix[0].split('.', 2)[1]) abis.extend(sorted(list(abi3s))) abis.append('none') if not noarch: arch = get_platform() # Current version, current API (built specifically for our Python): for abi in abis: supported.append(('%s%s' % (impl, versions[0]), abi, arch)) # No abi / arch, but requires our implementation: for i, version in enumerate(versions): supported.append(('%s%s' % (impl, version), 'none', 'any')) if i == 0: # Tagged specifically as being cross-version compatible # (with just the major version specified) supported.append(('%s%s' % (impl, versions[0][0]), 'none', 'any')) # No abi / arch, generic Python for i, version in enumerate(versions): supported.append(('py%s' % (version,), 'none', 'any')) if i == 0: supported.append(('py%s' % (version[0]), 'none', 'any')) return supported supported_tags = get_supported() supported_tags_noarch = get_supported(noarch=True) python3.3/site-packages/pip/basecommand.py 0000644 00000014662 15154344632 0014464 0 ustar 00 """Base Command class, and related routines""" import os import sys import tempfile import traceback import time import optparse from pip import cmdoptions from pip.locations import running_under_virtualenv from pip.log import logger from pip.download import PipSession from pip.exceptions import (BadCommand, InstallationError, UninstallationError, CommandError, PreviousBuildDirError) from pip.backwardcompat import StringIO from pip.baseparser import ConfigOptionParser, UpdatingDefaultsHelpFormatter from pip.status_codes import (SUCCESS, ERROR, UNKNOWN_ERROR, VIRTUALENV_NOT_FOUND, PREVIOUS_BUILD_DIR_ERROR) from pip.util import get_prog __all__ = ['Command'] class Command(object): name = None usage = None hidden = False def __init__(self): parser_kw = { 'usage': self.usage, 'prog': '%s %s' % (get_prog(), self.name), 'formatter': UpdatingDefaultsHelpFormatter(), 'add_help_option': False, 'name': self.name, 'description': self.__doc__, } self.parser = ConfigOptionParser(**parser_kw) # Commands should add options to this option group optgroup_name = '%s Options' % self.name.capitalize() self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name) # Add the general options gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, self.parser) self.parser.add_option_group(gen_opts) def _build_session(self, options): session = PipSession() # Handle custom ca-bundles from the user if options.cert: session.verify = options.cert # Handle timeouts if options.timeout: session.timeout = options.timeout # Handle configured proxies if options.proxy: session.proxies = { "http": options.proxy, "https": options.proxy, } # Determine if we can prompt the user for authentication or not session.auth.prompting = not options.no_input return session def setup_logging(self): pass def parse_args(self, args): # factored out for testability return self.parser.parse_args(args) def main(self, args): options, args = self.parse_args(args) level = 1 # Notify level += options.verbose level -= options.quiet level = logger.level_for_integer(4 - level) complete_log = [] logger.add_consumers( (level, sys.stdout), (logger.DEBUG, complete_log.append), ) if options.log_explicit_levels: logger.explicit_levels = True self.setup_logging() #TODO: try to get these passing down from the command? # without resorting to os.environ to hold these. if options.no_input: os.environ['PIP_NO_INPUT'] = '1' if options.exists_action: os.environ['PIP_EXISTS_ACTION'] = ' '.join(options.exists_action) if options.require_venv: # If a venv is required check if it can really be found if not running_under_virtualenv(): logger.fatal('Could not find an activated virtualenv (required).') sys.exit(VIRTUALENV_NOT_FOUND) if options.log: log_fp = open_logfile(options.log, 'a') logger.add_consumers((logger.DEBUG, log_fp)) else: log_fp = None exit = SUCCESS store_log = False try: status = self.run(options, args) # FIXME: all commands should return an exit status # and when it is done, isinstance is not needed anymore if isinstance(status, int): exit = status except PreviousBuildDirError: e = sys.exc_info()[1] logger.fatal(str(e)) logger.info('Exception information:\n%s' % format_exc()) store_log = True exit = PREVIOUS_BUILD_DIR_ERROR except (InstallationError, UninstallationError): e = sys.exc_info()[1] logger.fatal(str(e)) logger.info('Exception information:\n%s' % format_exc()) store_log = True exit = ERROR except BadCommand: e = sys.exc_info()[1] logger.fatal(str(e)) logger.info('Exception information:\n%s' % format_exc()) store_log = True exit = ERROR except CommandError: e = sys.exc_info()[1] logger.fatal('ERROR: %s' % e) logger.info('Exception information:\n%s' % format_exc()) exit = ERROR except KeyboardInterrupt: logger.fatal('Operation cancelled by user') logger.info('Exception information:\n%s' % format_exc()) store_log = True exit = ERROR except: logger.fatal('Exception:\n%s' % format_exc()) store_log = True exit = UNKNOWN_ERROR if store_log: log_file_fn = options.log_file text = '\n'.join(complete_log) try: log_file_fp = open_logfile(log_file_fn, 'w') except IOError: temp = tempfile.NamedTemporaryFile(delete=False) log_file_fn = temp.name log_file_fp = open_logfile(log_file_fn, 'w') logger.fatal('Storing debug log for failure in %s' % log_file_fn) log_file_fp.write(text) log_file_fp.close() if log_fp is not None: log_fp.close() return exit def format_exc(exc_info=None): if exc_info is None: exc_info = sys.exc_info() out = StringIO() traceback.print_exception(*exc_info, **dict(file=out)) return out.getvalue() def open_logfile(filename, mode='a'): """Open the named log file in append mode. If the file already exists, a separator will also be printed to the file to separate past activity from current activity. """ filename = os.path.expanduser(filename) filename = os.path.abspath(filename) dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) exists = os.path.exists(filename) log_fp = open(filename, mode) if exists: log_fp.write('%s\n' % ('-' * 60)) log_fp.write('%s run on %s\n' % (sys.argv[0], time.strftime('%c'))) return log_fp python3.3/site-packages/pip/commands/search.py 0000644 00000011200 15154344632 0015242 0 ustar 00 import sys import textwrap import pip.download from pip.basecommand import Command, SUCCESS from pip.util import get_terminal_size from pip.log import logger from pip.backwardcompat import xmlrpclib, reduce, cmp from pip.exceptions import CommandError from pip.status_codes import NO_MATCHES_FOUND from pip._vendor import pkg_resources from distutils.version import StrictVersion, LooseVersion class SearchCommand(Command): """Search for PyPI packages whose name or summary contains <query>.""" name = 'search' usage = """ %prog [options] <query>""" summary = 'Search PyPI for packages.' def __init__(self, *args, **kw): super(SearchCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '--index', dest='index', metavar='URL', default='https://pypi.python.org/pypi', help='Base URL of Python Package Index (default %default)') self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): if not args: raise CommandError('Missing required argument (search query).') query = args index_url = options.index pypi_hits = self.search(query, index_url) hits = transform_hits(pypi_hits) terminal_width = None if sys.stdout.isatty(): terminal_width = get_terminal_size()[0] print_results(hits, terminal_width=terminal_width) if pypi_hits: return SUCCESS return NO_MATCHES_FOUND def search(self, query, index_url): pypi = xmlrpclib.ServerProxy(index_url) hits = pypi.search({'name': query, 'summary': query}, 'or') return hits def transform_hits(hits): """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages = {} 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) # 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 def print_results(hits, name_column_width=25, terminal_width=None): installed_packages = [p.project_name for p in pkg_resources.working_set] for hit in hits: name = hit['name'] summary = hit['summary'] or '' 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) line = '%s - %s' % (name.ljust(name_column_width), summary) try: logger.notify(line) if name in installed_packages: dist = pkg_resources.get_distribution(name) logger.indent += 2 try: latest = highest_version(hit['versions']) if dist.version == latest: logger.notify('INSTALLED: %s (latest)' % dist.version) else: logger.notify('INSTALLED: %s' % dist.version) logger.notify('LATEST: %s' % latest) finally: logger.indent -= 2 except UnicodeEncodeError: pass def compare_versions(version1, version2): try: return cmp(StrictVersion(version1), StrictVersion(version2)) # in case of abnormal version number, fall back to LooseVersion except ValueError: pass try: return cmp(LooseVersion(version1), LooseVersion(version2)) except TypeError: # certain LooseVersion comparions raise due to unorderable types, # fallback to string comparison return cmp([str(v) for v in LooseVersion(version1).version], [str(v) for v in LooseVersion(version2).version]) def highest_version(versions): return reduce((lambda v1, v2: compare_versions(v1, v2) == 1 and v1 or v2), versions) python3.3/site-packages/pip/commands/freeze.py 0000644 00000011070 15154344632 0015262 0 ustar 00 import re import sys import pip from pip.req import InstallRequirement from pip.log import logger from pip.basecommand import Command from pip.util import get_installed_distributions from pip._vendor import pkg_resources class FreezeCommand(Command): """Output installed packages in requirements format.""" name = 'freeze' usage = """ %prog [options]""" summary = 'Output installed packages in requirements format.' def __init__(self, *args, **kw): super(FreezeCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '-r', '--requirement', dest='requirement', action='store', default=None, metavar='file', help="Use the order in the given requirements file and it's comments when generating output.") self.cmd_opts.add_option( '-f', '--find-links', dest='find_links', action='append', default=[], metavar='URL', help='URL for finding packages, which will be added to the output.') self.cmd_opts.add_option( '-l', '--local', dest='local', action='store_true', default=False, help='If in a virtualenv that has global access, do not output globally-installed packages.') self.parser.insert_option_group(0, self.cmd_opts) def setup_logging(self): logger.move_stdout_to_stderr() def run(self, options, args): requirement = options.requirement find_links = options.find_links or [] local_only = options.local ## FIXME: Obviously this should be settable: find_tags = False skip_match = None skip_regex = options.skip_requirements_regex if skip_regex: skip_match = re.compile(skip_regex) dependency_links = [] f = sys.stdout for dist in pkg_resources.working_set: if dist.has_metadata('dependency_links.txt'): dependency_links.extend(dist.get_metadata_lines('dependency_links.txt')) for link in find_links: if '#egg=' in link: dependency_links.append(link) for link in find_links: f.write('-f %s\n' % link) installations = {} for dist in get_installed_distributions(local_only=local_only): req = pip.FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags) installations[req.name] = req if requirement: req_f = open(requirement) for line in req_f: if not line.strip() or line.strip().startswith('#'): f.write(line) continue if skip_match and skip_match.search(line): f.write(line) continue elif line.startswith('-e') or line.startswith('--editable'): if line.startswith('-e'): line = line[2:].strip() else: line = line[len('--editable'):].strip().lstrip('=') line_req = InstallRequirement.from_editable(line, default_vcs=options.default_vcs) 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('--find-links') or line.startswith('--index-url')): f.write(line) continue else: line_req = InstallRequirement.from_line(line) if not line_req.name: logger.notify("Skipping line because it's not clear what it would install: %s" % line.strip()) logger.notify(" (add #egg=PackageName to the URL to avoid this warning)") continue if line_req.name not in installations: logger.warn("Requirement file contains %s, but that package is not installed" % line.strip()) continue f.write(str(installations[line_req.name])) del installations[line_req.name] f.write('## The following requirements were added by pip --freeze:\n') for installation in sorted(installations.values(), key=lambda x: x.name): f.write(str(installation)) python3.3/site-packages/pip/commands/__pycache__/show.cpython-33.pyc 0000644 00000010064 15154344632 0021245 0 ustar 00 � 7�Re� c @ sn d d l Z d d l m Z d d l m Z d d l m Z Gd d � d e � Z d d � Z d d � Z d S( i N( u Command( u logger( u pkg_resourcesc sJ | Ee Z d Z d Z d Z d Z d Z � f d d � Z d d � Z � S( u ShowCommandu6 Show information about one or more installed packages.u showu$ %prog [options] <package> ...u* Show information about installed packages.c s^ t t | � j | | � | j j d d d d d d d d d d �| j j d | j � d S( Nu -fu --filesu destu filesu actionu store_trueu defaultu helpu7 Show the full list of installed files for each package.i F( u superu ShowCommandu __init__u cmd_optsu add_optionu Falseu parseru insert_option_group( u selfu argsu kw( u __class__( u* /tmp/pip-zej_zi-build/pip/commands/show.pyu __init__ s u ShowCommand.__init__c C s= | s t j d � d S| } t | � } t | | j � d S( Nu. ERROR: Please provide a package name or names.( u loggeru warnu search_packages_infou print_resultsu files( u selfu optionsu argsu queryu results( ( u* /tmp/pip-zej_zi-build/pip/commands/show.pyu run s u ShowCommand.run( u __name__u __module__u __qualname__u __doc__u nameu usageu summaryu __init__u run( u __locals__( ( u __class__u* /tmp/pip-zej_zi-build/pip/commands/show.pyu ShowCommand s u ShowCommandc c s� t d d � t j D� � } x� | D]� } | j � } | | k r# | | } i | j d 6| j d 6| j d 6d d � | j � D� d 6} t j j | j | j � d d � } t j j | � r� | | d <n | Vq# q# Wd S( u� Gather details from installed distributions. Print distribution name, version, location, and installed files. Installed files requires a pip generated 'installed-files.txt' in the distributions '.egg-info' directory. c S s% g | ] } | j j � | f � q S( ( u project_nameu lower( u .0u p( ( u* /tmp/pip-zej_zi-build/pip/commands/show.pyu <listcomp>, s u( search_packages_info.<locals>.<listcomp>u nameu versionu locationc S s g | ] } | j � q S( ( u project_name( u .0u dep( ( u* /tmp/pip-zej_zi-build/pip/commands/show.pyu <listcomp>5 s u requiresu .egg-infou installed-files.txtu filesN( u dictu pkg_resourcesu working_setu loweru project_nameu versionu locationu requiresu osu pathu joinu egg_nameu isfile( u queryu installed_packagesu nameu normalized_nameu distu packageu filelist( ( u* /tmp/pip-zej_zi-build/pip/commands/show.pyu search_packages_info$ s$ u search_packages_infoc C s� x� | D]� } t j d � t j d | d � t j d | d � t j d | d � t j d d j | d � � | r t j d � d | k r� x? t | d � D] } t j d | j � � q� Wq� t j d � q q Wd S( uD Print the informations from installed distributions found. u ---u Name: %su nameu Version: %su versionu Location: %su locationu Requires: %su , u requiresu Files:u filesu %su! Cannot locate installed-files.txtN( u loggeru notifyu joinu openu strip( u distributionsu list_all_filesu distu line( ( u* /tmp/pip-zej_zi-build/pip/commands/show.pyu print_results@ s u print_results( u osu pip.basecommandu Commandu pip.logu loggeru pip._vendoru pkg_resourcesu ShowCommandu search_packages_infou print_results( ( ( u* /tmp/pip-zej_zi-build/pip/commands/show.pyu <module> s python3.3/site-packages/pip/commands/__pycache__/bundle.cpython-33.pyc 0000644 00000005074 15154344632 0021543 0 ustar 00 � 7�Re� c @ s� d d l Z d d l m Z m Z d d l m Z m Z d d l m Z d d l m Z d d l m Z Gd d � d e � Z d S( i N( u build_prefixu src_prefix( u display_pathu backup_dir( u logger( u InstallationError( u InstallCommandc sV | Ee Z d Z d Z d Z d Z d Z d Z � f d d � Z � f d d � Z � S( u BundleCommandu9 Create pybundles (archives containing multiple packages).u bundleu: %prog [options] <bundle name>.pybundle <package>...u DEPRECATED. Create pybundles.c s� t t | � j | | � | j j d � } t t d � | _ | j j d � } t t d � | _ | j j i | j | j 6| j | j 6� d S( Nu --buildu -bundleu --src( u superu BundleCommandu __init__u parseru get_optionu backup_diru build_prefixu defaultu src_prefixu set_defaultsu dest( u selfu argsu kwu build_optu src_opt( u __class__( u, /tmp/pip-zej_zi-build/pip/commands/bundle.pyu __init__ s u BundleCommand.__init__c s� t j d d � | s% t d � � n d | _ t j d t | j � t | j � f � | j d � | _ t t | � j | | � } | S( Nu 1.6u� DEPRECATION: 'pip bundle' and support for installing from *.pybundle files is deprecated. See https://github.com/pypa/pip/pull/1046u You must give a bundle filenameuB Putting temporary build files in %s and source/develop files in %si T( u loggeru deprecatedu InstallationErroru Trueu ignore_installedu notifyu display_pathu build_diru src_diru popu bundle_filenameu superu BundleCommandu run( u selfu optionsu argsu requirement_set( u __class__( u, /tmp/pip-zej_zi-build/pip/commands/bundle.pyu run s u BundleCommand.runT( u __name__u __module__u __qualname__u __doc__u nameu usageu summaryu Trueu bundleu __init__u run( u __locals__( ( u __class__u, /tmp/pip-zej_zi-build/pip/commands/bundle.pyu BundleCommand s u BundleCommand( u textwrapu pip.locationsu build_prefixu src_prefixu pip.utilu display_pathu backup_diru pip.logu loggeru pip.exceptionsu InstallationErroru pip.commands.installu InstallCommandu BundleCommand( ( ( u, /tmp/pip-zej_zi-build/pip/commands/bundle.pyu <module> s python3.3/site-packages/pip/commands/__pycache__/search.cpython-33.pyc 0000644 00000015226 15154344632 0021537 0 ustar 00 � 7�Re� c @ s d d l Z d d l Z d d l Z d d l m Z m Z d d l m Z d d l m Z d d l m Z m Z m Z d d l m Z d d l m Z d d l m Z d d l m Z m Z Gd d � d e � Z d d � Z d d d d � Z d d � Z d d � Z d S( i N( u Commandu SUCCESS( u get_terminal_size( u logger( u xmlrpclibu reduceu cmp( u CommandError( u NO_MATCHES_FOUND( u pkg_resources( u StrictVersionu LooseVersionc sV | Ee Z d Z d Z d Z d Z d Z � f d d � Z d d � Z d d � Z � S( u SearchCommandu@ Search for PyPI packages whose name or summary contains <query>.u searchu %prog [options] <query>u Search PyPI for packages.c s[ t t | � j | | � | j j d d d d d d d d d �| j j d | j � d S( Nu --indexu destu indexu metavaru URLu defaultu https://pypi.python.org/pypiu helpu3 Base URL of Python Package Index (default %default)i ( u superu SearchCommandu __init__u cmd_optsu add_optionu parseru insert_option_group( u selfu argsu kw( u __class__( u, /tmp/pip-zej_zi-build/pip/commands/search.pyu __init__ s u SearchCommand.__init__c C s� | s t d � � n | } | j } | j | | � } t | � } d } t j j � rg t � d } n t | d | �| r� t St S( Nu) Missing required argument (search query).i u terminal_width( u CommandErroru indexu searchu transform_hitsu Noneu sysu stdoutu isattyu get_terminal_sizeu print_resultsu SUCCESSu NO_MATCHES_FOUND( u selfu optionsu argsu queryu index_urlu pypi_hitsu hitsu terminal_width( ( u, /tmp/pip-zej_zi-build/pip/commands/search.pyu run"