main.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Primary application entrypoint.
  2. """
  3. import locale
  4. import logging
  5. import os
  6. import sys
  7. from typing import List, Optional
  8. from pip._internal.cli.autocompletion import autocomplete
  9. from pip._internal.cli.main_parser import parse_command
  10. from pip._internal.commands import create_command
  11. from pip._internal.exceptions import PipError
  12. from pip._internal.utils import deprecation
  13. logger = logging.getLogger(__name__)
  14. # Do not import and use main() directly! Using it directly is actively
  15. # discouraged by pip's maintainers. The name, location and behavior of
  16. # this function is subject to change, so calling it directly is not
  17. # portable across different pip versions.
  18. # In addition, running pip in-process is unsupported and unsafe. This is
  19. # elaborated in detail at
  20. # https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
  21. # That document also provides suggestions that should work for nearly
  22. # all users that are considering importing and using main() directly.
  23. # However, we know that certain users will still want to invoke pip
  24. # in-process. If you understand and accept the implications of using pip
  25. # in an unsupported manner, the best approach is to use runpy to avoid
  26. # depending on the exact location of this entry point.
  27. # The following example shows how to use runpy to invoke pip in that
  28. # case:
  29. #
  30. # sys.argv = ["pip", your, args, here]
  31. # runpy.run_module("pip", run_name="__main__")
  32. #
  33. # Note that this will exit the process after running, unlike a direct
  34. # call to main. As it is not safe to do any processing after calling
  35. # main, this should not be an issue in practice.
  36. def main(args: Optional[List[str]] = None) -> int:
  37. if args is None:
  38. args = sys.argv[1:]
  39. # Configure our deprecation warnings to be sent through loggers
  40. deprecation.install_warning_logger()
  41. autocomplete()
  42. try:
  43. cmd_name, cmd_args = parse_command(args)
  44. except PipError as exc:
  45. sys.stderr.write(f"ERROR: {exc}")
  46. sys.stderr.write(os.linesep)
  47. sys.exit(1)
  48. # Needed for locale.getpreferredencoding(False) to work
  49. # in pip._internal.utils.encoding.auto_decode
  50. try:
  51. locale.setlocale(locale.LC_ALL, "")
  52. except locale.Error as e:
  53. # setlocale can apparently crash if locale are uninitialized
  54. logger.debug("Ignoring error %s when setting locale", e)
  55. command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
  56. return command.main(cmd_args)