python shell命令行_使用Python创建Shell命令行应用程序并单击

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 program called test and I have commands called subtest1 and subtest2

I was able to make it work from terminal like:

$ test subtest1

$ test subtest2

But what I was thinking about is a shell, so I could do:

$ test

>> subtest1

>> subtest2

Is this possible with click?

解决方案

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值