show.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import os
  2. from pip.basecommand import Command
  3. from pip.log import logger
  4. from pip._vendor import pkg_resources
  5. class ShowCommand(Command):
  6. """Show information about one or more installed packages."""
  7. name = 'show'
  8. usage = """
  9. %prog [options] <package> ..."""
  10. summary = 'Show information about installed packages.'
  11. def __init__(self, *args, **kw):
  12. super(ShowCommand, self).__init__(*args, **kw)
  13. self.cmd_opts.add_option(
  14. '-f', '--files',
  15. dest='files',
  16. action='store_true',
  17. default=False,
  18. help='Show the full list of installed files for each package.')
  19. self.parser.insert_option_group(0, self.cmd_opts)
  20. def run(self, options, args):
  21. if not args:
  22. logger.warn('ERROR: Please provide a package name or names.')
  23. return
  24. query = args
  25. results = search_packages_info(query)
  26. print_results(results, options.files)
  27. def search_packages_info(query):
  28. """
  29. Gather details from installed distributions. Print distribution name,
  30. version, location, and installed files. Installed files requires a
  31. pip generated 'installed-files.txt' in the distributions '.egg-info'
  32. directory.
  33. """
  34. installed_packages = dict(
  35. [(p.project_name.lower(), p) for p in pkg_resources.working_set])
  36. for name in query:
  37. normalized_name = name.lower()
  38. if normalized_name in installed_packages:
  39. dist = installed_packages[normalized_name]
  40. package = {
  41. 'name': dist.project_name,
  42. 'version': dist.version,
  43. 'location': dist.location,
  44. 'requires': [dep.project_name for dep in dist.requires()],
  45. }
  46. filelist = os.path.join(
  47. dist.location,
  48. dist.egg_name() + '.egg-info',
  49. 'installed-files.txt')
  50. if os.path.isfile(filelist):
  51. package['files'] = filelist
  52. yield package
  53. def print_results(distributions, list_all_files):
  54. """
  55. Print the informations from installed distributions found.
  56. """
  57. for dist in distributions:
  58. logger.notify("---")
  59. logger.notify("Name: %s" % dist['name'])
  60. logger.notify("Version: %s" % dist['version'])
  61. logger.notify("Location: %s" % dist['location'])
  62. logger.notify("Requires: %s" % ', '.join(dist['requires']))
  63. if list_all_files:
  64. logger.notify("Files:")
  65. if 'files' in dist:
  66. for line in open(dist['files']):
  67. logger.notify(" %s" % line.strip())
  68. else:
  69. logger.notify("Cannot locate installed-files.txt")