2015-09-10 56 views
2

我想用Python的Click library解析一些命令行參數,並將提供的值保存在對象中。使用Python的點擊庫保存命令行選項的值

我的第一個猜測是做這樣的:

import click 

class Configuration(object): 

    def __init__(self): 

     # configuration variables 
     self.MyOption = None 

     # method call 
     self.parseCommandlineArguments() 

    @click.command() 
    @click.option('--myoption', type=click.INT, default=5) 
    def parseCommandlineArguments(self, myoption): 

     # save option's value in the object 
     self.MyOption = myoption 

# create an instance 
configuration = Configuration() 
print(configuration.MyOption) 

然而,這是不行的,而不是我得到:

TypeError: parseCommandlineArguments() takes exactly 2 arguments (1 given) 

顯然,通過self的裝飾功能不正確的方法來做到這一點。如果我從方法參數中刪除self,那麼我可以做print(myoption),它會在屏幕上打印5,但是我的Configuration()類的任何實例都不會知道該值。

處理這個問題的正確方法是什麼?我認爲它與context handling in Click有關,但我無法根據提供的示例使其工作。

回答

5

如果我正確地理解了你,你需要一個命令行工具,它將採用配置選項,然後對這些選項進行一些操作。如果這是你的目標,那麼看看我發佈的例子。此示例使用command groups並通過每個命令傳遞一個context對象。點擊有令人敬畏的文檔,請務必閱讀。

import click 
import json 


class Configuration(object): 
    """ 
    Having a custom context class is usually not needed. 
    See the complex application documentation: 
     http://click.pocoo.org/5/complex/ 
    """ 
    my_option = None 
    number = None 
    is_awesome = False 
    uber_var = 900 

    def make_conf(self): 
     self.uber_var = self.my_option * self.number 

pass_context = click.make_pass_decorator(Configuration, ensure=True) 


@click.group(chain=True) 
@click.option('-m', '--myoption', type=click.INT, default=5) 
@click.option('-n', '--number', type=click.INT, default=0) 
@click.option('-a', '--is-awesome', is_flag=True) 
@pass_context 
def cli(ctx, myoption, number, is_awesome): 
    """ 
    this is where I will save the configuration 
    and do whatever processing that is required 
    """ 
    ctx.my_option = myoption 
    ctx.number = number 
    ctx.is_awesome = is_awesome 
    ctx.make_conf() 
    pass 


@click.command('save') 
@click.argument('output', type=click.File('wb')) 
@pass_context 
def save(ctx, output): 
    """save the configuration to a file""" 
    json.dump(ctx.__dict__, output, indent=4, sort_keys=True) 
    return click.secho('configuration saved', fg='green') 


@click.command('show') 
@pass_context 
def show(ctx): 
    """print the configuration to stdout""" 
    return click.echo(json.dumps(ctx.__dict__, indent=4, sort_keys=True)) 

cli.add_command(save) 
cli.add_command(show) 

在此之後安裝您可以運行類似以下的命令:

mycli -m 30 -n 40 -a show 
mycli -m 30 -n 40 -a save foo.json 
mycli -m 30 -n 40 -a show save foo.json 

complex example是開發一個高度可配置的多鏈接命令行工具,一個很好的示範。