Wolkenarchitekt
Wolkenarchitekt

Reputation: 21248

Python Commandline script: file/directory autocompletion on user input

I'm writing a Python program which is running inside a Bash Terminal (and it already depends on Bash as its environment). There I have a little setup routine, which asks the user for a directory which is located on his filesystem. This is how I read the input:

print "Input:",
input = sys.stdin.readline().strip()

Now I want the user to be able to autocomplete his input with the name of existing files or directories. What's the best way to do that? Do I need to lookup the directories/files myself and use the package cmd (as in this example)? Or is there an easier, "built-in" way to do that?

It would also be ok if i was able to use the Bash autocompletion with os.system. But everything that i tried so far wasn't successful. This is what I tried:

os.system("read -e -p \"Input:\" INPUT")

But it's strange: Bash complains read: 1: Illegal option -e, although the command works inside a simple Bash script. But I need the -e modifier for the completion.

Any suggestions how I can do file/dirname autocompletion in an Python Console Program?

Upvotes: 4

Views: 4285

Answers (1)

samplebias
samplebias

Reputation: 37929

You want to checkout the readline module. I answered a similar question here, which shows how to do filename/dirname auto-completion of paths. Let me know if you need more detail.

Upvotes: 5

Related Questions