__main__.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from __future__ import annotations
  2. import logging
  3. import sys
  4. from argparse import ArgumentParser
  5. from findpython import Finder
  6. from findpython.__version__ import __version__
  7. logger = logging.getLogger("findpython")
  8. def setup_logger(level: int = logging.DEBUG) -> None:
  9. """
  10. Setup the logger.
  11. """
  12. handler = logging.StreamHandler()
  13. handler.setFormatter(logging.Formatter("%(name)s-%(levelname)s: %(message)s"))
  14. logger.addHandler(handler)
  15. logger.setLevel(level)
  16. def split_str(value: str) -> list[str]:
  17. return value.split(",")
  18. def cli(argv: list[str] | None = None) -> int:
  19. """
  20. Command line interface for findpython.
  21. """
  22. parser = ArgumentParser(
  23. "findpython", description="A utility to find python versions on your system"
  24. )
  25. parser.add_argument(
  26. "-V", "--version", action="version", version=f"%(prog)s {__version__}"
  27. )
  28. parser.add_argument(
  29. "-a", "--all", action="store_true", help="Show all matching python versions"
  30. )
  31. parser.add_argument(
  32. "--resolve-symlink", action="store_true", help="Resolve all symlinks"
  33. )
  34. parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output")
  35. parser.add_argument(
  36. "--no-same-file",
  37. action="store_true",
  38. help="Eliminate the duplicated results with the same file contents",
  39. )
  40. parser.add_argument(
  41. "--no-same-python",
  42. action="store_true",
  43. help="Eliminate the duplicated results with the same sys.executable",
  44. )
  45. parser.add_argument("--providers", type=split_str, help="Select provider(s) to use")
  46. parser.add_argument("version_spec", nargs="?", help="Python version spec or name")
  47. args = parser.parse_args(argv)
  48. if args.verbose:
  49. setup_logger()
  50. finder = Finder(
  51. resolve_symlinks=args.resolve_symlink,
  52. no_same_file=args.no_same_file,
  53. selected_providers=args.providers,
  54. )
  55. if args.all:
  56. find_func = finder.find_all
  57. else:
  58. find_func = finder.find # type: ignore[assignment]
  59. python_versions = find_func(args.version_spec)
  60. if not python_versions:
  61. print("No matching python version found", file=sys.stderr)
  62. return 1
  63. if not isinstance(python_versions, list):
  64. python_versions = [python_versions]
  65. print("Found matching python versions:", file=sys.stderr)
  66. for python_version in python_versions:
  67. print(python_version)
  68. return 0
  69. def main() -> None:
  70. """
  71. Main function.
  72. """
  73. sys.exit(cli())
  74. if __name__ == "__main__":
  75. main()