简体   繁体   English

optparse和bash选项卡完成的怪异行为

[英]Weird behaviour with optparse and bash tab completion

I am building a script for users new to Linux, so please understand why I am asking this :) 我正在为刚接触Linux的用户构建脚本,所以请理解我为什么要问这个问题:)

My script runs like this: 我的脚本运行如下:

python script.py -f filename.txt

I am using the optparse module for this. 我正在为此使用optparse模块。 However, I noticed the following when doing tab completion. 但是,在完成制表符时,我注意到以下内容。

The tab completion works when I do: 当我执行以下操作时,制表符补全有效:

python script.py <tab completion> # Tab completion works normally as expected

But it does not work when I do it like this: 但是当我这样做时它不起作用:

python script.py -f <tab completion> # No type of tab completion works here.

I really don't want my users typing the name of the input file. 我真的不希望我的用户键入输入文件的名称。 Tab completion is a must. 制表符必须是必填项。 How can I get it working or what am I doing wrong here? 我如何使其正常工作或在这里做错了什么?

This is more to do with how bash works than how python works. 这更多与bash的工作方式有关,而与python的工作方式有关。 Experimenting a bit, it looks as if the second and further TAB actually causes bash to expand. 稍作试验,似乎第二个和更远的TAB实际上导致bash扩展。

Edit : The probable reason that bash is only expanding the *.py and *.pyc files is because the first word on the line is python . 编辑 :bash仅扩展*.py*.pyc文件的可能原因是因为该行的第一个单词是python If you add #! /usr/bin/env python 如果添加#! /usr/bin/env python #! /usr/bin/env python to the first line of the python script, chmod +x script.py and then try ./scipt.py -f and tab completion, what happens then? #! /usr/bin/env python到python脚本的第一行chmod +x script.py ,然后尝试./scipt.py -f和制表符./scipt.py -f ,然后会发生什么? I suspect it'll work just fine. 我怀疑它会很好。

This is related to bash completion. 这与bash完成有关。 Try to see whether you have your own bash_completion script and look for python. 尝试查看您是否拥有自己的bash_completion脚本并查找python。

The common completion file is in /etc/bash_completion and you should have something like 通用/etc/bash_completion文件位于/etc/bash_completion ,您应该具有以下内容

if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
    . /etc/bash_completion
fi

in your .bashrc (_profile or whatever). 在您的.bashrc中(_profile或其他)。

Now you can redefine some behavior by adding your own script. 现在,您可以通过添加自己的脚本来重新定义某些行为。 Take a look at the /etc/bash_completion file for some inspiration. 看一下/etc/bash_completion文件,以获取一些启发。 :) :)

如果您希望用户获得简化的体验(即他们不需要了解Shell的工作方式以及在特定安装中如何配置外壳),则您的程序应构建一个输入文件列表,并向用户显示该文件他们的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM