python - 使用 argparse 完成 Bash 选项卡不显示目录中的所有文件

标签 python bash shell argparse

我注意到,如果我使用 argparse 参数,bash tab 补全返回的文件较少。我怎样才能改变/控制它?

最小示例代码

me@here:~/test$ cat argparsetest.py 
import argparse
parser.add_argument('-i', help='input', required=True)

bash 完成示例:

# shows all the files 
me@here:~/test$ python argparsetest.py 
argparsetest.py  result.png       u1.py  

# does not show the image result.png I am actually interested in
me@here:~/test$ python argparsetest.py -i
argparsetest.py  u1.py            

已经有两个类似的问题,但我没有发现它们有帮助。

最佳答案

这与 argparse 甚至 Python 本身无关。您可能启用了“programmable bash completion”,并且由于您的命令行以“python”开头,所以完成规则很困惑。

解决这个问题的最简单方法是在 python 文件的顶部添加:

#!/usr/bin/env python

,然后使 Python 脚本可执行:

me@here:~/test$ chmod u+x argparsetest.py 

然后直接调用它,而不显式调用“python”:

me@here:~/test$ ./argparsetest.py<TAB>
argparsetest.py  result.png       u1.py  

me@here:~/test$ ./argparsetest.py -i<TAB>
argparsetest.py  result.png       u1.py  

或者,您可以完全关闭 bash 补全

complete -r

而且,如果您想在以后的 session 中禁用它,请注释掉或删除您的 ~/.bashrc 或/etc/bashrc 中可能如下所示的行:

if [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
fi

关于python - 使用 argparse 完成 Bash 选项卡不显示目录中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10399244/

相关文章:

python - Python内存管理

linux - bash中的“for option”和bash中的echo

linux - "more"支持颜色的命令选项?

python - 连接到插槽时如何向 Qt PySide 内置信号添加参数

python - 通过文件路径导入模块时使用 Python 多处理

linux - 如何使用 Sed 命令将文件准确地 append 到最后一句话的尾部

bash - Shell 脚本 - 在文件中智能替换并在第二个文件中查找

linux - 如何从 su 命令获取密码?

windows - telnet 输出使用 .bat 文件将其保存到文件

python - 将变量设置为等于找到关键字的行