Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. #
  4. # Copyright (c) 2008 Doug Hellmann All rights reserved.
  5. #
  6. """
  7. """
  8.  
  9. __version__ = "$Id$"
  10. #end_pymotw_header
  11.  
  12. import readline
  13. import logging
  14. import os
  15.  
  16. LOG_FILENAME = '/tmp/completer.log'
  17. HISTORY_FILENAME = '/tmp/completer.hist'
  18.  
  19. logging.basicConfig(filename=LOG_FILENAME,
  20. level=logging.DEBUG,
  21. )
  22.  
  23. def get_history_items():
  24. num_items = readline.get_current_history_length() + 1
  25. return [ readline.get_history_item(i)
  26. for i in xrange(1, num_items)
  27. ]
  28.  
  29. class HistoryCompleter(object):
  30.  
  31. def __init__(self):
  32. self.matches = []
  33. return
  34.  
  35. def complete(self, text, state):
  36. response = None
  37. if state == 0:
  38. history_values = get_history_items()
  39. logging.debug('history: %s', history_values)
  40. if text:
  41. self.matches = sorted(h
  42. for h in history_values
  43. if h and h.startswith(text))
  44. else:
  45. self.matches = []
  46. logging.debug('matches: %s', self.matches)
  47. try:
  48. response = self.matches[state]
  49. except IndexError:
  50. response = None
  51. logging.debug('complete(%s, %s) => %s',
  52. repr(text), state, repr(response))
  53. return response
  54.  
  55. def input_loop():
  56. if os.path.exists(HISTORY_FILENAME):
  57. readline.read_history_file(HISTORY_FILENAME)
  58. print 'Max history file length:', readline.get_history_length()
  59. print 'Startup history:', get_history_items()
  60. try:
  61. while True:
  62. line = raw_input('Prompt ("stop" to quit): ')
  63. if line == 'stop':
  64. break
  65. if line:
  66. print 'Adding "%s" to the history' % line
  67. finally:
  68. print 'Final history:', get_history_items()
  69. readline.write_history_file(HISTORY_FILENAME)
  70.  
  71. # Register our completer function
  72. readline.set_completer(HistoryCompleter().complete)
  73.  
  74. # Use the tab key for completion
  75. readline.parse_and_bind('tab: complete')
  76.  
  77. # Prompt the user for text
  78. input_loop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement