开发者

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 :)

My script runs like this:

python script.py -f filename.txt

I am using the optparse module for this. 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开发者_如何学Go

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. Experimenting a bit, it looks as if the second and further TAB actually causes bash to expand.

Edit: The probable reason that bash is only expanding the *.py and *.pyc files is because the first word on the line is python. If you add #! /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? I suspect it'll work just fine.


This is related to bash completion. Try to see whether you have your own bash_completion script and look for python.

The common completion file is in /etc/bash_completion and you should have something like

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

in your .bashrc (_profile or whatever).

Now you can redefine some behavior by adding your own script. Take a look at the /etc/bash_completion file for some inspiration. :)


If you want users to have a simplified experience (i.e. that they not need to understand how the shell works and how it might be configured in their particular installation), then your program should build a list of input files and display that to the user for their selection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜