filepath autocompletion using users input

2019-02-02 13:59发布

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

2条回答
女痞
2楼-- · 2019-02-02 14:04

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()
查看更多
再贱就再见
3楼-- · 2019-02-02 14:11

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? ')
查看更多
登录 后发表回答