Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 273
Wolkenarchitekt Avatar asked Oct 27 '25 06:10

Wolkenarchitekt


1 Answers

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.

like image 136
samplebias Avatar answered Oct 29 '25 18:10

samplebias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!