Creating a shell command line application with Python and Click

前端 未结 4 1154
野的像风
野的像风 2021-02-06 00:48

I\'m using click (http://click.pocoo.org/3/) to create a command line application, but I don\'t know how to create a shell for this application.
Suppose I\'m writing a progr

4条回答
  •  野的像风
    2021-02-06 01:13

    This is not impossible with click, but there's no built-in support for that either. The first you would have to do is making your group callback invokable without a subcommand by passing invoke_without_command=True into the group decorator (as described here). Then your group callback would have to implement a REPL. Python has the cmd framework for doing this in the standard library. Making the click subcommands available there involves overriding cmd.Cmd.default, like in the code snippet below. Getting all the details right, like help, should be doable in a few lines.

    import click
    import cmd
    
    class REPL(cmd.Cmd):
        def __init__(self, ctx):
            cmd.Cmd.__init__(self)
            self.ctx = ctx
    
        def default(self, line):
            subcommand = cli.commands.get(line)
            if subcommand:
                self.ctx.invoke(subcommand)
            else:
                return cmd.Cmd.default(self, line)
    
    @click.group(invoke_without_command=True)
    @click.pass_context
    def cli(ctx):
        if ctx.invoked_subcommand is None:
            repl = REPL(ctx)
            repl.cmdloop()
    
    @cli.command()
    def a():
        """The `a` command prints an 'a'."""
        print "a"
    
    @cli.command()
    def b():
        """The `b` command prints a 'b'."""
        print "b"
    
    if __name__ == "__main__":
        cli()
    

提交回复
热议问题