_argcomplete.py 3.5 KB

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