Python 的 raw_input() 中的 Tab 补全
我知道我可以这样做,以确保在Python中获得制表符完成的效果。
import readline
COMMANDS = ['extra', 'extension', 'stuff', 'errors',
'email', 'foobar', 'foo']
def complete(text, state):
for cmd in COMMANDS:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 1
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
raw_input('Enter section name: ')
我现在对使用目录进行制表符补全感兴趣。 (/home/user/doc >tab)
我将如何去做这样的任务?
i know i can do this to get the effect of tab completion in python sure.
import readline
COMMANDS = ['extra', 'extension', 'stuff', 'errors',
'email', 'foobar', 'foo']
def complete(text, state):
for cmd in COMMANDS:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 1
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
raw_input('Enter section name: ')
I am now interested in doing tab completion with directories. (/home/user/doc >tab)
How would i go about doing such a task?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
以下是如何执行文件系统路径增量补全的快速示例。我修改了您的示例,将其组织到一个类中,其中名为
complete_[name]
的方法指示顶级命令。我已将完成函数切换为使用内部读取行缓冲区来确定整体完成的状态,这使得状态逻辑更简单一些。路径补全位于
_complete_path(path)
方法中,并且我已连接 extra 命令来对其参数执行路径补全。我确信代码可以进一步简化,但它应该为您提供一个不错的起点:
用法:
更新如果用户输入
/
,它将完成从根开始的路径:Here is a quick example of how to perform incremental completion of file system paths. I've modified your example, organizing it into a class where methods named
complete_[name]
indicate top-level commands.I've switched the completion function to use the internal readline buffer to determine the state of the overall completion, which makes the state logic a bit simpler. The path completion is in the
_complete_path(path)
method, and I've hooked up the extra command to perform path completions on its arguments.I'm sure the code could be further simplified but it should provide you a decent starting point:
Usage:
Update It will complete paths from the root if the user types
/
:这足以使用 raw_input() 启用内置目录选项卡补全:
This is enough to enable built in directory tab completion with raw_input():
该版本适用于python3,使用pathlib,并且是tab完成文件/目录的简约版本。它基于上面的一些答案,但仅适用于文件/目录。
This version is for python3, uses pathlib, and a minimalistic version that tab completes files/dirs. It is based on some of the above answers, but only works for files/dirs.
对于路径完成
请注意,我已经改进了 https://gist.github.com/iamatypeofwalrus 中找到的代码/5637895
For path completion
Note that I've refined the code found at https://gist.github.com/iamatypeofwalrus/5637895
在某些系统上,您需要使用不同的绑定。例如,我没有 GNU readline,所以我需要使用不同的 parse_and_bind 文本:
On Some Systems™ you need to use different bindings. For example, I don't have GNU readline, so I need to use a different parse_and_bind text:
在 Python 3.11 中,以下代码适用于目录和文件选择。
In Python 3.11, the below code works for both directory and file selection.