Skip to content

Instantly share code, notes, and snippets.

@mingyuan-xia
Created March 11, 2017 18:11
Show Gist options
  • Save mingyuan-xia/e8cac85ec8cd3f8ae21760580a529846 to your computer and use it in GitHub Desktop.
Save mingyuan-xia/e8cac85ec8cd3f8ae21760580a529846 to your computer and use it in GitHub Desktop.
Autocompletion support for file paths for Python cmd library
# -*- coding: utf-8 -*-
import os
import glob
def _append_slash_if_dir(p):
if p and os.path.isdir(p) and p[-1] != os.sep:
return p + os.sep
else:
return p
def autocomplete_file_path(self, text, line, begidx, endidx):
""" File path autocompletion, used with the cmd module complete_* series functions"""
# http://stackoverflow.com/questions/16826172/filename-tab-completion-in-cmd-cmd-of-python
before_arg = line.rfind(" ", 0, begidx)
if before_arg == -1:
return # arg not found
fixed = line[before_arg+1:begidx] # fixed portion of the arg
arg = line[before_arg+1:endidx]
pattern = arg + '*'
completions = []
for path in glob.glob(pattern):
path = _append_slash_if_dir(path)
completions.append(path.replace(fixed, "", 1))
return completions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment