Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filepath autocompletion using users input

(python)

I'm looking to grab a users input for a filepath. It seems pretty basic, but I can't seem to get readline or rlcompleter working.

Pretty much: variable = raw_input(' Filepath: ') and then the filepath has autocomplete functions like it would in a shell.

I'm not restricted to python, I'm willing to use any language so long as I can set a variable as the filepath and grab the filepath using autocomplete functionality.

I've seen this: Tab completion in Python's raw_input() which helped me get an idea of what to look for, although the problem was that it required a command in front of the filepath such as "extra". I need to set the variable as the filepath. You'd think it'd be pretty simple, but I haven't found much on it anywhere, and the few that I have found weren't exactly what I was looking for.

In bash there was a read -e command that can be run in a command line, but it's not recognized in a script which was odd. It's exactly what I was looking for, if only it could be utilized inside of a script to set the variable equal to the autocompleted filepath.

like image 253
DeJay Avatar asked Jul 11 '11 21:07

DeJay


2 Answers

Something like this?

import readline, glob
def complete(text, state):
    return (glob.glob(text+'*')+[None])[state]

readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
raw_input('file? ')
like image 93
Luke Avatar answered Nov 18 '22 20:11

Luke


This is only loosely python and I suspect there are probably ways that someone could hack this and cause you all kinds of problems... or something but this is a way I got the bash and python to play well together.

import subprocess

the_file=subprocess.check_output('read -e -p "Enter path file:" var ; echo $var',shell=True).rstrip()
like image 38
jeffpkamp Avatar answered Nov 18 '22 20:11

jeffpkamp