_argcomplete.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. """allow bash-completion for argparse with argcomplete if installed
  2. needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail
  3. to find the magic string, so _ARGCOMPLETE env. var is never set, and
  4. this does not need special code.
  5. Function try_argcomplete(parser) should be called directly before
  6. the call to ArgumentParser.parse_args().
  7. The filescompleter is what you normally would use on the positional
  8. arguments specification, in order to get "dirname/" after "dirn<TAB>"
  9. instead of the default "dirname ":
  10. optparser.add_argument(Config._file_or_dir, nargs='*'
  11. ).completer=filescompleter
  12. Other, application specific, completers should go in the file
  13. doing the add_argument calls as they need to be specified as .completer
  14. attributes as well. (If argcomplete is not installed, the function the
  15. attribute points to will not be used).
  16. SPEEDUP
  17. =======
  18. The generic argcomplete script for bash-completion
  19. (/etc/bash_completion.d/python-argcomplete.sh )
  20. uses a python program to determine startup script generated by pip.
  21. You can speed up completion somewhat by changing this script to include
  22. # PYTHON_ARGCOMPLETE_OK
  23. so the the python-argcomplete-check-easy-install-script does not
  24. need to be called to find the entry point of the code and see if that is
  25. marked with PYTHON_ARGCOMPLETE_OK
  26. INSTALL/DEBUGGING
  27. =================
  28. To include this support in another application that has setup.py generated
  29. scripts:
  30. - add the line:
  31. # PYTHON_ARGCOMPLETE_OK
  32. near the top of the main python entry point
  33. - include in the file calling parse_args():
  34. from _argcomplete import try_argcomplete, filescompleter
  35. , call try_argcomplete just before parse_args(), and optionally add
  36. filescompleter to the positional arguments' add_argument()
  37. If things do not work right away:
  38. - switch on argcomplete debugging with (also helpful when doing custom
  39. completers):
  40. export _ARC_DEBUG=1
  41. - run:
  42. python-argcomplete-check-easy-install-script $(which appname)
  43. echo $?
  44. will echo 0 if the magic line has been found, 1 if not
  45. - sometimes it helps to find early on errors using:
  46. _ARGCOMPLETE=1 _ARC_DEBUG=1 appname
  47. which should throw a KeyError: 'COMPLINE' (which is properly set by the
  48. global argcomplete script).
  49. """
  50. from __future__ import absolute_import, division, print_function
  51. import sys
  52. import os
  53. from glob import glob
  54. class FastFilesCompleter(object):
  55. "Fast file completer class"
  56. def __init__(self, directories=True):
  57. self.directories = directories
  58. def __call__(self, prefix, **kwargs):
  59. """only called on non option completions"""
  60. if os.path.sep in prefix[1:]:
  61. prefix_dir = len(os.path.dirname(prefix) + os.path.sep)
  62. else:
  63. prefix_dir = 0
  64. completion = []
  65. globbed = []
  66. if "*" not in prefix and "?" not in prefix:
  67. # we are on unix, otherwise no bash
  68. if not prefix or prefix[-1] == os.path.sep:
  69. globbed.extend(glob(prefix + ".*"))
  70. prefix += "*"
  71. globbed.extend(glob(prefix))
  72. for x in sorted(globbed):
  73. if os.path.isdir(x):
  74. x += "/"
  75. # append stripping the prefix (like bash, not like compgen)
  76. completion.append(x[prefix_dir:])
  77. return completion
  78. if os.environ.get("_ARGCOMPLETE"):
  79. try:
  80. import argcomplete.completers
  81. except ImportError:
  82. sys.exit(-1)
  83. filescompleter = FastFilesCompleter()
  84. def try_argcomplete(parser):
  85. argcomplete.autocomplete(parser, always_complete_options=False)
  86. else:
  87. def try_argcomplete(parser):
  88. pass
  89. filescompleter = None