在python中使用创建命令行应用程序Click单击下载
问题描述:
我正在使用接受名称作为输入的Click库在Python中创建命令行应用程序,但如果未输入任何名称,则会返回默认值。在python中使用创建命令行应用程序Click单击下载
这是我到目前为止的代码。
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!
$你好鲍勃-r 3
Hello Bob!
Hello Bob!
Hello Bob!
这正是我想要的是。
现在,我希望能够像stdin一样接受来自以下示例的输入。
$ echo John |你好
Hello John!
$呼应约翰|你好-r 3
Hello John!
Hello John!
Hello John!
答
的问题是,管道之前,命令结果将您的应用程序中,而不是作为它的参数消耗。由于您的应用程序不会在其内部使用任何输入,因此您输入的所有内容都将被丢弃。
如果你想让你的应用程序'可移植',只需在其中插入一个raw_input
,因为这个函数从标准输入读取。
为了让你的程序看起来像猫,你可以这样做:
@click.command()
@click.argument('string', required=False)
@click.option('-r', '--repeat', default=1, help='How many times should be greeted.')
def cli(string, repeat):
'''This string greets you.'''
if not string:
string = raw_input()
for i in xrange(repeat):
click.echo('Hello %s!' % string)
另一种选择是一个选项将串并设置提示为True:
@click.command()
@click.option('--string', prompt=True)
@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)
这样,如果用户不会提供一个字符串,他将被提示输入,这使得您的应用程序也可以移动。唯一的问题是,它将打印到标准输出STRING:
,有时是不可接受的(你可以定义一个空字符串与prompt=''
一起显示,但是,因为我知道,没有机会摆脱:
)。
顺便说一句,以达到同样的事情,用你的代码事情是这样的,你可以这样做:
python hello.py `echo bob`
echo bob
进行评估第一和它的结果将组成论据打招呼。py
答
这是一个相当古老的问题,但我会尽力回答它。
我很新奇Click,所以,我认为,我的解决方案可以极大地提高。无论如何,它确实是你想要的。这里是:
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()