gpt4 book ai didi

python - python -m 模块的命令行自动完成

转载 作者:行者123 更新时间:2023-12-04 11:41:46 27 4
gpt4 key购买 nike

是否可以获得 python -m package.subpackage.module 的命令行自动完成功能? ?

这与 python ./package/subpackage/module.py 相似,但不相同。 ,它会自动完成目录和文件路径。然而与 -m ,python 将库的模块作为具有适当命名空间和导入路径的脚本运行。

我希望能够做到python -m package.s[TAB]并自动完成到 subpackage .

此功能是否内置于某处,或者如何设置?

最佳答案

如评论部分所述,您需要扩展 bash 完成 工具。然后,您将创建一个脚本来处理您需要的情况(即:当最后一个参数是 -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

(警告。这个脚本有一个缺陷,它不适用于包含空格的文件名)。要测试它,请在 中运行它当前 环境:
. ./python_completion.sh

并测试它:
python -m packag[TAB]

Here是一个以这种方式继续的教程。

关于python - python -m 模块的命令行自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53269417/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com