main.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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=None):
  37. # type: (Optional[List[str]]) -> int
  38. if args is None:
  39. args = sys.argv[1:]
  40. # Configure our deprecation warnings to be sent through loggers
  41. deprecation.install_warning_logger()
  42. autocomplete()
  43. try:
  44. cmd_name, cmd_args = parse_command(args)
  45. except PipError as exc:
  46. sys.stderr.write(f"ERROR: {exc}")
  47. sys.stderr.write(os.linesep)
  48. sys.exit(1)
  49. # Needed for locale.getpreferredencoding(False) to work
  50. # in pip._internal.utils.encoding.auto_decode
  51. try:
  52. locale.setlocale(locale.LC_ALL, "")
  53. except locale.Error as e:
  54. # setlocale can apparently crash if locale are uninitialized
  55. logger.debug("Ignoring error %s when setting locale", e)
  56. command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
  57. return command.main(cmd_args)