希望这会给你一个开始做你想做的事,它非常粗糙,需要针对所有这些边缘情况进行改进,但希望你会发现它有一些用处。我只是希望我已经回答了我认为你问的问题。
#!/usr/bin/env python
import readline
import os.path
import glob
class Completer(object):
def __init__(self):
self.matches = []
def complete_path(self, text, state):
if state == 0:
self.matches = glob.glob(text + "*")
if state < len(self.matches):
if os.path.isdir(self.matches[state]):
return self.matches[state] + "/"
else:
return self.matches[state]
else:
self.matches = []
return None
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode emacs')
# Allow '/'
default_delims = readline.get_completer_delims()
delims = default_delims.translate(None, "/")
readline.set_completer_delims(delims)
readline.set_completer(Completer().complete_path)
while True:
line = raw_input('Enter Path: ["^C" to quit] : ')
print 'Line: "%s"' % line