Python 自动化运维 —— 命令行工具

1. click 模块

click 模块和argparse功能相同,但更为易用,使用click分为两个步骤 :
1) 使用@click.command()装饰一个函数,使之成为命令行接口;
2) 使用@click.option()等装饰函数,为其添加命令行选项等。

import click
@click.command()
@click.option('--count',defalut=1,help='Number of greetings.')
@click.option('--name',prompt='Your name',help='The persion to greet')
def hellp(count,name):
    '''simple program thar greets NAME for total of COUNT times...'''
        for x in range(count):
            click.echo('Hello %s !!!' % name)
if __name__ == '__main__':
    hellp()

实例中,函数hellp接受两个参数count和name,他们的取值从命令行中获取,使用了click中的 command、option、echo,使用了prompt选项,因此在没有指定name参数时,click会提示我们在交互模式下输入。

通过nargs配置参数的个数,通过type设置参数的类型:

import click
@click.command()
@click.option('--pos',nargs=2,type=float)
def findme(pos):
    click.echo('%s / %s' % pos)

type=click.Choice(['md5','sha1']) 只能选择两者其一。

如果需要从命令行输入密码,使用argparse 只能像输入普通参数一样,在click中只需要将prompt设为True,设置hide_input为True,就可以隐藏输入,达到输入密码的效果,设置confirmation_prompt为True,就可以两次验证,比如注册账号时需要输入两次密码。

2. prompt_toolkit 模块

    prompt_toolkit 是一个处理交互式场景的开源库,用来取×××源的 redline 和 curses。特点包括:
    1) 语法高亮
    2) 支持多行编辑
    3) 支持代码补全
    4) 支持自动提示
    5) 支持鼠标移动光标
    6) 支持Emacs与 vi 风格快捷键
    7) 支持查询历史
    8) 对 Unicode 支持友好

简单示例:

#!/usr/bin/python
from __future__ import unicode_literals
from prompt_toolkit import prompt
while True:
    user_input = prompt('>')
        print("user_input")

这样交互式输入的时候就能使用Ctrl+a 或者 Ctrl+e等快捷键了,注意:在Python 2 中需要加入 from future import unicode_literals

实现历史输入:

from prompt_toolkit import prompt
from __future__ import unicode_literals
from prompt_toolkit.history import FileHistory

while True:
    user_input = prompt('>',
    history=FileHistory('history.txt'),
    print(user_input)

还可以实现输入提示:

from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory

while True:
    user_input = prompt('>',
    history=FileHistory('history.txt'),
    auto_suggest=AutoSuggestFromHistory(),
    )
        print(user_input)

最后实现自动输入自动补全:

from prompt_toolkit import prompt
from __future__ import unicode_literals
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.contrib.completers import WordCompleter

SQLCompleter = WordCompleter(['select','update','drop','insert','delete'],ignore_case=True)
while True:
    user_input = prompt('>',
    history=FileHistory('history.txt'),
    auto_suggest=AutoSuggestFromHistory(),
    completer=SQLCompleter,
    )
    print(user_input)

转载于:https://blog.51cto.com/thewolf/2116551

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值