Hat*_*sut 12 python bash autocomplete bash-completion
是否有可能获得命令行自动完成功能python -m package.subpackage.module?
这类似于但不一样,python ./package/subpackage/module.py它会自动完成目录和文件路径。但是-m,使用 时,python 将库的模块作为具有适当命名空间和导入路径的脚本来运行。
我希望能够python -m package.s[TAB]自动完成subpackage.
此功能是否内置于某处,或者我该如何设置?
正如评论部分所述,您需要扩展bash-completion工具。然后,您将创建一个脚本来处理您需要的情况(即:当最后一个参数为 时-m)。
下面的这个小示例显示了自定义完成脚本的开始。我们来命名一下吧python_completion.sh。
_python_target() {
local cur prev opts
# Retrieving the current typed argument
cur="${COMP_WORDS[COMP_CWORD]}"
# Retrieving the previous typed argument ("-m" for example)
prev="${COMP_WORDS[COMP_CWORD-1]}"
# Preparing an array to store available list for completions
# COMREPLY will be checked to suggest the list
COMPREPLY=()
# Here, we'll only handle the case of "-m"
# Hence, the classic autocompletion is disabled
# (ie COMREPLY stays an empty array)
if [[ "$prev" != "-m" ]]
then
return 0
fi
# Retrieving paths and converts their separators into dots
# (if packages doesn't exist, same thing, empty array)
if [[ ! -e "./package" ]]
then
return 0
fi
# Otherwise, we retrieve first the paths starting with "./package"
# and converts their separators into dots
opts="$(find ./package -type d | sed -e 's+/+.+g' -e 's/^\.//' | head)"
# We store the whole list by invoking "compgen" and filling
# COMREPLY with its output content.
COMPREPLY=($(compgen -W "$opts" -- "$cur"))
}
complete -F _python_target python
Run Code Online (Sandbox Code Playgroud)
(警告。此脚本有一个缺陷,它不适用于包含空格的文件名)。要测试它,请在当前环境中运行它:
. ./python_completion.sh
Run Code Online (Sandbox Code Playgroud)
并测试一下:
python -m packag[TAB]
Run Code Online (Sandbox Code Playgroud)
这是一个以这种方式继续的教程。