2015-09-10 57 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是开发一个高度可配置的多链接命令行工具,一个很好的示范。