tags:

views:

67

answers:

3

Hi

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

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?

+1  A: 

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.

Vatine
It seems to list Python files, (py and pyc) but not of any other type.
sukhbir
And yes, your observation is correct. So what is happening here?
sukhbir
It works! Thank you! Perfect :)
sukhbir
+1  A: 

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

mathk
But I will be distributing the script to other users. How do I handle the above on their part?
sukhbir
A: 

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.

Dennis Williamson
I did that first but I thought bash completion is the norm that is why I stuck to that.
sukhbir
@PulpFiction: Bash has two types of completion. The builtin variety and the programmable variety. Unless functions are supplied to provide behavior other than the default, all you're going to get is the default behavior. If programmable completion functions provide behavior other than what you want, you'll have to override it. This is largely a user-driven thing. You shouldn't (as an application) mess with how a user has their environment configured unless that is what the user wants. The answer you accepted is the other correct way to handle this situation.
Dennis Williamson