12

(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.

Community
  • 1
  • 1
DeJay
  • 121
  • 1
  • 1
  • 3
  • do you mean you would like to implement tilde-expansion, file-name-globbing, shell-variable expansion etc? Pls, add expected input... – Fredrik Pihl Jul 11 '11 at 21:32

2 Answers2

29

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? ')
Luke
  • 11,374
  • 2
  • 48
  • 61
  • This implementation of a completer is inferior to the default one in that it doesn't seem to properly complete paths outside the current directory. But thank you nevertheless for the interesting piece'o'code. – eMPee584 Mar 13 '15 at 15:30
  • This does not seem to work for relative (ie `../')` or `~/`. Does anyone know why? – wovenhead May 29 '15 at 13:39
  • out-of-cwd completion works for me on OSX :) but colours in the output doesnt :( – J.J Aug 25 '15 at 20:21
  • To get it working with ~ you have to use `glob.glob(os.path.expanduser(text)+'*')` About relative path you have to define your own list of delimiters not containing '/' (default is `\t\n \`~!@#$%^&*()-=+[{]}\\|;:\'",<>/?`) – WIP Feb 25 '19 at 09:56
1

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()
jeffpkamp
  • 2,732
  • 2
  • 27
  • 51