How to design object oriented subparsers for argparse?

与世无争的帅哥 提交于 2019-12-04 07:09:51

问题


Problem

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.


回答1:


A cmd class and parser:

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)

sample runs:

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

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.



来源:https://stackoverflow.com/questions/46595691/how-to-design-object-oriented-subparsers-for-argparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!