【问题标题】:Bash tab completion with argparse does not show all the files in the directory使用 argparse 完成 Bash 选项卡不会显示目录中的所有文件
【发布时间】:2012-05-11 01:42:32
【问题描述】:

我注意到如果我使用 argparse 参数,bash 选项卡完成返回的文件更少。我怎样才能改变/控制它?

最小示例代码

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            

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

【问题讨论】:

  • 我无法重现您的行为。 python 2.7.2,bash 补全版本1:1.3-1ubuntu6。带有和不带有 -i 的选项卡都包含 png 文件。此外,您的最小代码中缺少像 parser = argparse.ArgumentParser(description='do things') 这样的行。

标签: python bash shell argparse


【解决方案1】:

这与 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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2019-11-07
    • 2021-09-04
    相关资源
    最近更新 更多