如何使 python 命令行程序自动完成任意事物而不是解释器 [英] How to make a python, command-line program autocomplete arbitrary things NOT interpreter

查看:28
本文介绍了如何使 python 命令行程序自动完成任意事物而不是解释器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在 python 解释器(在 unix 上)中设置 python 对象的自动完成.

I am aware of how to setup autocompletion of python objects in the python interpreter (on unix).

  • Google 显示了许多关于如何执行此操作的说明.
  • 不幸的是,参考文献太多,很难找到我需要做的事情,这略有不同.

我需要知道如何在用 python 编写的命令行程序中启用、制表符/自动完成任意项目.

I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.

我的具体用例是一个需要发送电子邮件的命令行 python 程序.我希望能够在用户键入部分电子邮件地址(并可选择按下 TAB 键)时自动完成电子邮件地址(我在磁盘上有地址).

My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).

我不需要它在 windows 或 mac 上运行,只需要在 linux 上运行.

I do not need it to work on windows or mac, just linux.

推荐答案

使用 Python 的 readline 绑定.例如,

Use Python's readline bindings. For example,

import readline

def completer(text, state):
    options = [i for i in commands if i.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None

readline.parse_and_bind("tab: complete")
readline.set_completer(completer)

官方模块文档并没有更详细,请参阅阅读文档 了解更多信息.

The official module docs aren't much more detailed, see the readline docs for more info.

这篇关于如何使 python 命令行程序自动完成任意事物而不是解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆