register_python_argcomplete.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. # PYTHON_ARGCOMPLETE_OK
  3. # Copyright 2012-2023, Andrey Kislyuk and argcomplete contributors.
  4. # Licensed under the Apache License. See https://github.com/kislyuk/argcomplete for more info.
  5. """
  6. Register a Python executable for use with the argcomplete module.
  7. To perform the registration, source the output of this script in your bash shell
  8. (quote the output to avoid interpolation).
  9. Example:
  10. $ eval "$(register-python-argcomplete my-favorite-script.py)"
  11. For Tcsh
  12. $ eval `register-python-argcomplete --shell tcsh my-favorite-script.py`
  13. For Fish
  14. $ register-python-argcomplete --shell fish my-favourite-script.py > ~/.config/fish/my-favourite-script.py.fish
  15. """
  16. import argparse
  17. import sys
  18. import argcomplete
  19. # PEP 366
  20. __package__ = "argcomplete.scripts"
  21. def main():
  22. parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  23. parser.add_argument(
  24. "--no-defaults",
  25. dest="use_defaults",
  26. action="store_false",
  27. default=True,
  28. help="when no matches are generated, do not fallback to readline's default completion (affects bash only)",
  29. )
  30. parser.add_argument(
  31. "--complete-arguments",
  32. nargs=argparse.REMAINDER,
  33. help="arguments to call complete with; use of this option discards default options (affects bash only)",
  34. )
  35. parser.add_argument(
  36. "-s",
  37. "--shell",
  38. choices=("bash", "zsh", "tcsh", "fish", "powershell"),
  39. default="bash",
  40. help="output code for the specified shell",
  41. )
  42. parser.add_argument(
  43. "-e", "--external-argcomplete-script", help="external argcomplete script for auto completion of the executable"
  44. )
  45. parser.add_argument("executable", nargs="+", help="executable to completed (when invoked by exactly this name)")
  46. argcomplete.autocomplete(parser)
  47. if len(sys.argv) == 1:
  48. parser.print_help()
  49. sys.exit(1)
  50. args = parser.parse_args()
  51. sys.stdout.write(
  52. argcomplete.shellcode(
  53. args.executable, args.use_defaults, args.shell, args.complete_arguments, args.external_argcomplete_script
  54. )
  55. )
  56. if __name__ == "__main__":
  57. sys.exit(main())