本文介绍了如何为argparse设计面向对象的子解析器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个包含很多子命令的程序包管理器.我希望有一个类似于以下内容的类结构.
I'm building a package manager that has a lot of sub-commands. I would prefer to have a class structure similar to the following.
class ListCommand:
def __init__(self):
name = "list"
alias = "ls"
short_description = "A useful simple line that explains the command"
def help(self):
# Display help
def command(self):
# do stuff when command is called
我该如何编写子解析器来处理类似这样的事情?我在网上找到了示例不用子分析器就可以做类似的事情.
How do I write subparser to work with something like this ? I found an example online that does something similar without subparsers.
推荐答案
cmd类和解析器:
import argparse
class Cmd:
def __init__(self,name):
self.name = name
def __call__(self, args):
# do stuff when command is called
print('Executing %s'%self)
print('args %s'% args)
def make_sup(self,sp):
self.parser = sp.add_parser(self.name)
self.parser.add_argument('--foo')
self.parser.set_defaults(action=self)
def __repr__(self):
return '<Cmd> %s'%self.name
cmds = []
cmds.append(Cmd('list'))
cmds.append(Cmd('foo'))
cmds.append(Cmd('bar'))
print(cmds)
parser = argparse.ArgumentParser()
sp = parser.add_subparsers(dest='cmd')
for cmd in cmds:
cmd.make_sup(sp)
print(parser._defaults)
args = parser.parse_args()
print(args)
args.action(args)
示例运行:
1834:~/mypy$ python stack46595691.py list --foo xxxx
[<Cmd> list, <Cmd> foo, <Cmd> bar]
{}
Namespace(action=<Cmd> list, cmd='list', foo='xxxx')
Executing <Cmd> list
args Namespace(action=<Cmd> list, cmd='list', foo='xxxx')
1837:~/mypy$ python stack46595691.py bar
[<Cmd> list, <Cmd> foo, <Cmd> bar]
{}
Namespace(action=<Cmd> bar, cmd='bar', foo=None)
Executing <Cmd> bar
args Namespace(action=<Cmd> bar, cmd='bar', foo=None)
1838:~/mypy$ python stack46595691.py foo -h
[<Cmd> list, <Cmd> foo, <Cmd> bar]
{}
usage: stack46595691.py foo [-h] [--foo FOO]
optional arguments:
-h, --help show this help message and exit
--foo FOO
您可能还希望查看plac
,这是对ArgumentParser
, https://pypi.python.org/pypi/plac
You might also want to look at plac
, a package that subclasses ArgumentParser
, https://pypi.python.org/pypi/plac
它可以基于函数的参数构造子解析器.
It can construct subparsers based on the arguments of functions.
这篇关于如何为argparse设计面向对象的子解析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!