Skip to content

Instantly share code, notes, and snippets.

@mikeboers
Last active December 31, 2015 07:29
Show Gist options
  • Save mikeboers/7954560 to your computer and use it in GitHub Desktop.
Save mikeboers/7954560 to your computer and use it in GitHub Desktop.
Autocomplete of Python package/module names
function pym {
python -m $@
}
function _pym_complete {
local executable current previous options
executable=${COMP_WORDS[0]}
current="${COMP_WORDS[COMP_CWORD]}"
previous="${COMP_WORDS[COMP_CWORD-1]}"
COMPREPLY=()
if [[ ( "$executable" == python* && "$previous" == "-m" ) ||
( "$executable" == pym && ! "$current" == -* ) ]]; then
options="`python <<EOF
import os
import pkgutil
import sys
current = '$current'
if '.' in current:
package_name = current.rsplit('.', 1)[0]
try:
package = __import__(package_name, fromlist=['__name__'])
except:
exit()
else:
package_name = ''
package = None
def walk_packages(paths, match, prefix=''):
for loader, name, ispkg in pkgutil.iter_modules(paths, prefix):
if not name.startswith(match):
continue
yield loader, name, ispkg
if ispkg:
for x in walk_packages([os.path.join(loader.path, name.split('.')[-1])], match, name + '.'):
yield x
for loader, name, ispkg in walk_packages(
package and getattr(package, '__path__', ()),
current,
package_name and (package_name + '.'),
):
if ispkg:
continue
if name.endswith('.__main__'):
print name.rsplit('.', 1)[0]
else:
print name
EOF
`"
COMPREPLY=( $(compgen -W "${options}") )
return 0
fi
}
complete -F _pym_complete pym
complete -F _pym_complete python
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment