bash 使用用户输入的文件路径自动完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6656819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:21:07  来源:igfitidea点击:

filepath autocompletion using users input

pythonbashinputautocomplete

提问by DeJay

(python)

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

我正在寻找用户输入的文件路径。这看起来很基本,但我似乎无法让 readline 或 rlcompleter 工作。

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

差不多: variable = raw_input(' Filepath: ') 然后文件路径具有自动完成功能,就像在 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.

我不限于 python,我愿意使用任何语言,只要我可以将变量设置为文件路径并使用自动完成功能获取文件路径。

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.

我已经看到了这一点: Python 的 raw_input() 中的 Tab 补全,它帮助我了解要查找的内容,尽管问题是它需要在文件路径前面添加一个命令,例如“额外”。我需要将变量设置为文件路径。你会认为它很简单,但我在任何地方都没有找到太多关于它的东西,而且我找到的几个并不是我想要的。

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.

在 bash 中有一个可以在命令行中运行的 read -e 命令,但它在奇怪的脚本中无法识别。这正是我正在寻找的,如果可以在脚本中使用它来将变量设置为等于自动完成的文件路径就好了。

回答by Luke

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? ')

回答by jeffpkamp

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.

这只是松散的python,我怀疑可能有办法有人可以破解它并给你带来各种各样的问题......但这是我让bash和python一起玩的一种方式。

import subprocess

the_file=subprocess.check_output('read -e -p "Enter path file:" var ; echo $var',shell=True).rstrip()