python argparse中的自定义选项卡完成 [英] Custom tab completion in python argparse

查看:32
本文介绍了python argparse中的自定义选项卡完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python 脚本中与 argparse 配合使用 shell 选项卡完成?

How to get shell tab completion cooperating with argparse in a Python script?

#!/usr/bin/env python
import argparse

def main(**args):
    pass

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('positional', choices=['spam', 'eggs'])
    parser.add_argument('--optional', choices=['foo1', 'foo2', 'bar'])
    args = parser.parse_args()
    main(**vars(args))

在 .py 文件上设置可执行标志后,预期结果应该类似于:

With an executable flag set on the .py file, the expected results should be something like:

$ ./example.py sp<tab>             
   ->  completes to "./example.py spam"
$ ./example.py --op<tab> 
   ->  completes to "./example.py --optional"
$ ./example.py --optional b<tab>
   ->  completes to "./example.py --optional bar"
$ ./example.py --optional f<tab>   
   ->  completes to "./example.py --optional foo"
       and, additionally, prints  "foo1  foo2"  choices on stdout on a new line

推荐答案

看看 argcomplete 安德烈·基斯柳克 (Andrey Kislyuk).

Have a look at argcomplete by Andrey Kislyuk.

安装:

pip install argcomplete

在调用 parser.parse_args() 之前导入模块并在源代码中添加一行:

Import the module and add one line in your source before calling parser.parse_args():

#!/usr/bin/env python

import argparse as ap
import argcomplete

def main(**args):
  pass

if __name__ == '__main__':
  parser = ap.ArgumentParser()
  parser.add_argument('positional', choices=['spam', 'eggs'])
  parser.add_argument('--optional', choices=['foo1', 'foo2', 'bar'])
  argcomplete.autocomplete(parser)
  args = parser.parse_args()
  main(**vars(args))

为了确保 bash 知道这个脚本,你使用

and to make sure that bash knows about this script, you use

eval "$(register-python-argcomplete your_script)"

你应该把那行放在你的 ~/.bashrc 或按照 argcomplete 的文档并激活全局"完成.

you should put that line in your ~/.bashrc or follow argcomplete's docs and activate 'global' completion.

之后您按要求完成工作.

After that you completion works as requested.

它的工作方式是 eval 行创建一个使用 complete 注册的函数 _python_argcomlete.(运行 register-python-argcomplete your_script 以查看 eval-ed 到 bash 中的内容).自动完成功能会查找 bash 完成机制设置的环境变量,以查看是否需要采取行动.如果它起作用,它退出程序.如果它不动作,这是对程序的正常调用,该函数什么也不做,程序的正常流程继续.

The way this works is that the eval line creates a function _python_argcomlete which is registered using complete. (Run register-python-argcomplete your_script to just have a look at what gets eval-ed into bash). The autocomplete function looks for environment variables set by the bash completion mechanism to see if it needs to act. If it acts, it exits the program. If it doesn't act, this is a normal call to the program that function does nothing and the normal flow of the program continues.

这篇关于python argparse中的自定义选项卡完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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