How do I return a value when @click.option is used to pass a command line argument to a function?

后端 未结 4 2146
慢半拍i
慢半拍i 2021-02-20 04:31

I am trying to use click python package to pass a command line argument to a function. The example from official documentation works as explained. But nowhere in the documentati

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 04:59

    After looking through click's source code/reference I stumbled across the main() method of BaseCommand which takes the parameter, standalone_mode, that allows you to return values if disabled (it is True by default). Hope this helps someone in the future.

    Setup code:

    import sys
    import click
    
    @click.group(invoke_without_command=True)
    @click.option('--option1')
    @click.argument('arg1')
    def main(option1, arg1):
        class SpecialObject():
            def __init__(self, option, arg):
                self.option = option
                self.arg = arg
            def __repr__(self):
                return str(self.option)+str(self.arg)
    
        return SpecialObject(option1, arg1)
    
    @main.command()
    def subcmd():
        return [4,5,6]
    

    Test code:

    if __name__ == "__main__":
        commands = (
            ["--help"], 
            ["arg_val",],
            ["--option1","option1_val","arg1_val"],
            ["arg_val","subcmd"],
            ["arg_val","subcmd", "--help",], 
        )
        print(f'Click Version: {click.__version__}')
        print(f'Python Version: {sys.version}')
        for cmd in commands:
            print('-----------')
            print(f'Starting cmd:{cmd}')
            ret_val = main.main(cmd, standalone_mode=False)
            print(f"Returned: {type(ret_val)}, {ret_val}\n"
    

    Output:

    $ python __main__.py
    Click Version: 7.1.2
    Python Version: 3.9.1 (default, Dec 11 2020, 09:29:25) [MSC v.1916 64 bit (AMD64)]
    -----------
    Starting cmd:['--help']
    Usage: __main__.py [OPTIONS] ARG1 COMMAND [ARGS]...
    
    Options:
      --option1 TEXT
      --help          Show this message and exit.
    
    Commands:
      subcmd
    Returned: , 0
    
    -----------
    Starting cmd:['arg_val']
    Returned: .SpecialObject'>, Nonearg_val
    
    -----------
    Starting cmd:['--option1', 'option1_val', 'arg1_val']
    Returned: .SpecialObject'>, option1_valarg1_val
    
    -----------
    Starting cmd:['arg_val', 'subcmd']
    Returned: , [4, 5, 6]
    
    -----------
    Starting cmd:['arg_val', 'subcmd', '--help']
    Usage: __main__.py subcmd [OPTIONS]
    
    Options:
      --help  Show this message and exit.
    Returned: , 0
    

提交回复
热议问题