使用Click在python中创建命令行应用程序 [英] Creating command line application in python using Click

查看:100
本文介绍了使用Click在python中创建命令行应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Click 库在Python中创建一个命令行应用程序,该库接受名称作为输入,但是如果没有输入名称,它将返回默认值.

I am creating a command line application in Python using the Click library that accepts a name as input but if no name is entered it returns the default value.

这是我到目前为止的代码.

Here is the code I have so far.

hello.py

import click

@click.version_option(1.0)

@click.command()
@click.argument('string', default='World')
@click.option('-r', '--repeat', default=1, help='How many times should be greeted.')

def cli(string,repeat):
    '''This string greets you.'''
    for i in xrange(repeat): 
        click.echo('Hello %s!' % string)

if __name__ == '__main__':
    cli()

当我运行它时.

$您好

Hello World!

$你好鲍勃

Hello Bob!

$ hello Bob -r 3

Hello Bob!
Hello Bob!
Hello Bob!

这正是我想要的.

现在,我希望能够像以下示例一样接受来自stdin的输入.

Now, I would like to be able to accept input from stdin like the following examples.

$ echo John |你好

Hello John!

$ echo John |你好-r 3

Hello John!
Hello John!
Hello John!

推荐答案

这是一个很老的问题,但我还是会尝试回答.

Well this is quite an old question but I will try to answer it anyway.

我是Click的新手,因此,我认为,可以极大地改善我的解决方案.无论如何,它确实可以满足您的需求.在这里:

I'm sorta new to Click so, I reckon, my solution can be improved immensely. Anyway it does exactly what you want. Here it is:

import click


def get_name(ctx, param, value):
    if not value and not click.get_text_stream('stdin').isatty():
        return click.get_text_stream('stdin').read().strip()
    else:
        return value


@click.command()
@click.argument('name', callback=get_name, required=False)
@click.option('--repeat', '-r', default=1)
def say_hello(name, repeat):
    for i in range(repeat):
        click.echo('Hello {}'.format(name or 'World'))



if __name__ == "__main__":
    say_hello()

这篇关于使用Click在python中创建命令行应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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