2015-10-18 66 views
3

我正在使用接受名稱作爲輸入的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! 

回答

3

的問題是,管道之前,命令結果將您的應用程序中,而不是作爲它的參數消耗。由於您的應用程序不會在其內部使用任何輸入,因此您輸入的所有內容都將被丟棄。

如果你想讓你的應用程序'可移植',只需在其中插入一個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

0

這是一個相當古老的問題,但我會盡力回答它。

我很新奇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() 
相關問題