subparse


Namesubparse JSON
Version 0.6 PyPI version JSON
download
home_pagehttps://github.com/mmerickel/subparse
SummaryA command line helper library for extensible subcommands
upload_time2022-05-15 21:11:22
maintainer
docs_urlNone
authorMichael Merickel
requires_python>=3.8
licenseMIT
keywords argparse cli commandline subcommand
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            ========
subparse
========

A wrapper for argparse that provides decorator-based subcommand support.

Commands can be defined separately from their actual main functions,
enabling faster import times.

Basic Usage
===========

::

    from subparse import CLI

    class MyApp(object):
        def __init__(self, quiet=False):
            self.quiet = quiet

        def info(self, *msg):
            if not self.quiet:
                print('[info]', *msg)

    def context_factory(cli, args):
        return MyApp(args.quiet)

    def generic_options(parser):
        parser.add_argument('--quiet', action='store_true',
                            help='turn of debugging')

    cli = CLI(version='0.0', context_factory=context_factory)
    cli.add_generic_options(generic_options)

    @cli.command(__name__ + ':foo_main')
    def foo(parser):
        """
        a short description ending in a period.

        a longer description
        """
        parser.add_argument('--bar', action='store_true',
                            help='turn on bar')

    def foo_main(app, args):
        app.info('Hello World!')

    result = cli.run()
    sys.exit(result)

Lazy Decorators
===============

Commands can be defined lazily and picked up later. This removes ordering
restrictions between the commands and the cli object.

A module containing commands can be defined irrespective of the actual
``CLI`` instance:

::

    # myapp/info.py

    from subparse import command

    @command('myapp.info:foo_main')
    def foo(parser):
        """perform foo"""

Later, when an instance of a ``CLI`` is created, the commands can be loaded
and registered:

::

    cli = CLI()
    cli.load_commands('myapp.info')

Entry Points
============

Commands may also be defined in external modules and loaded via entry
points.

::

    from subparse import cli

    cli = CLI()
    cli.load_commands_from_entry_point('myapp.commands')

An extension application would then define the external module that should
be searched for commands. Again this allows the commands themselves to be
defined independently of the main functions, improving import speed.

An extension package should define a module containing the supported
commands:

::

    # barpkg/commands.py

    from subparse import command

    @command('barpkg.bar')
    def bar(parser):
        """perform bar"""

The package should also define the function to be called for each command.
Optionally in a separate module to avoid importing run-time dependencies
during parsing:

::

    # barpkg/bar.py

    def main(app, args):
        pass

The package can then broadcast the module ``barpkg.commands``
containing the supported commands:

::

    [myapp.commands]
    barpkg = barpkg.commands

Now when your extension package is installed the commands will automatically
become available.

Context Factory
===============

Each subcommand, when executed, is passed a context object which defines a
reusable API between subcommands. This is really the secret sauce of
``subparse`` that makes it really easy to build your own shared CLI features.

The ``context_factory`` argument to the ``subparse.CLI`` allows for defining
an object that is passed to all commands. This factory can also be a
generator, allowing it to ``yield`` the context object and then cleanup
after the command is complete. For example:

::

    import transaction

    def context_factory(cli, args):
        tm = transaction.TransactionManager(explicit=True)
        with tm:
            yield tm

In the above example the transaction manager is available to all subcommands
and it can commit/abort based on whether the command raises an exception.

Each subcommand can pass custom kwargs to the context factory via the
``context_kwargs`` argument. For example, if a single subcommand wishes to
opt-out of the transaction manager:

::

    def context_factory(cli, args, without_tm=False):
        if without_tm:
            yield

        tm = transaction.TransactionManager(explicit=True)
        with tm:
            yield tm

    @command(..., context_kwargs=dict(without_tm=True))
    def foo(parser):
        """" Run a command without the tm enabled."""

0.6 (2022-05-15)
================

- Drop Python 2.7, 3.4, 3.5, 3.6, 3.7.

- Add Python 3.8, 3.9, 3.10.

- Drop dependency on pkg_resources and use importlib.metadata.

- 100% test coverage.

0.5.3 (2019-03-09)
==================

- Output help to ``sys.stderr`` when parsing fails.

- Support passing ``context_kwargs`` to the ``command`` decorator. These
  arguments will be passed to the ``context_factory`` when the command is
  executed.

0.5.2 (2019-03-09)
==================

- Sort subcommands in help output.

0.5.1 (2019-03-08)
==================

- Use the ``argparse.RawTextHelpFormatter`` formatter class.

0.5 (2019-03-08)
================

- Add Python 3.7 support.

- Fix a deprecation warning coming from setuptools.

- Conform more closely to PEP-257 for docstring parsing.

- Modify how the help text is displayed using the
  ``argparse.RawDescriptionHelpFormatter`` formatter class.

0.4 (2018-05-03)
================

- Drop Python 2.6, 3.2 and 3.3 support.

- Add Python 3.4, 3.5, 3.6 support.

- Allow the ``context_factory`` to be a generator which yields the context.
  This allows the context to wrap the full lifecycle of the CLI.

0.3.3 (2013-08-12)
==================

No functional changes from 0.3.2.

- Improve documentation.

0.3.2 (2013-08-06)
==================

- Add `CLI.run` API for simply executing the command line.

0.3.1 (2013-08-06)
==================

- Improve the help output.

0.3 (2013-08-06)
================

- Rename subcommands to commands in the API.

0.2 (2013-08-06)
================

- Underscores in function names are converted to dashes in their respective
  subcommand names.
- Add `CLI.add_generic_options` API.
- Add a new `help` subcommand, allowing for `myapp help foo`.
- Allow relative imports in the subcommand specification.

0.1 (2013-08-05)
================

- Initial Commits

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/mmerickel/subparse",
    "name": "subparse",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "argparse,cli,commandline,subcommand",
    "author": "Michael Merickel",
    "author_email": "oss@m.merickel.org",
    "download_url": "https://files.pythonhosted.org/packages/6e/c8/15bbaeaf939a2925ff48a474b9790209b1829ec1edc1302137de64bd6984/subparse-0.6.tar.gz",
    "platform": null,
    "description": "========\nsubparse\n========\n\nA wrapper for argparse that provides decorator-based subcommand support.\n\nCommands can be defined separately from their actual main functions,\nenabling faster import times.\n\nBasic Usage\n===========\n\n::\n\n    from subparse import CLI\n\n    class MyApp(object):\n        def __init__(self, quiet=False):\n            self.quiet = quiet\n\n        def info(self, *msg):\n            if not self.quiet:\n                print('[info]', *msg)\n\n    def context_factory(cli, args):\n        return MyApp(args.quiet)\n\n    def generic_options(parser):\n        parser.add_argument('--quiet', action='store_true',\n                            help='turn of debugging')\n\n    cli = CLI(version='0.0', context_factory=context_factory)\n    cli.add_generic_options(generic_options)\n\n    @cli.command(__name__ + ':foo_main')\n    def foo(parser):\n        \"\"\"\n        a short description ending in a period.\n\n        a longer description\n        \"\"\"\n        parser.add_argument('--bar', action='store_true',\n                            help='turn on bar')\n\n    def foo_main(app, args):\n        app.info('Hello World!')\n\n    result = cli.run()\n    sys.exit(result)\n\nLazy Decorators\n===============\n\nCommands can be defined lazily and picked up later. This removes ordering\nrestrictions between the commands and the cli object.\n\nA module containing commands can be defined irrespective of the actual\n``CLI`` instance:\n\n::\n\n    # myapp/info.py\n\n    from subparse import command\n\n    @command('myapp.info:foo_main')\n    def foo(parser):\n        \"\"\"perform foo\"\"\"\n\nLater, when an instance of a ``CLI`` is created, the commands can be loaded\nand registered:\n\n::\n\n    cli = CLI()\n    cli.load_commands('myapp.info')\n\nEntry Points\n============\n\nCommands may also be defined in external modules and loaded via entry\npoints.\n\n::\n\n    from subparse import cli\n\n    cli = CLI()\n    cli.load_commands_from_entry_point('myapp.commands')\n\nAn extension application would then define the external module that should\nbe searched for commands. Again this allows the commands themselves to be\ndefined independently of the main functions, improving import speed.\n\nAn extension package should define a module containing the supported\ncommands:\n\n::\n\n    # barpkg/commands.py\n\n    from subparse import command\n\n    @command('barpkg.bar')\n    def bar(parser):\n        \"\"\"perform bar\"\"\"\n\nThe package should also define the function to be called for each command.\nOptionally in a separate module to avoid importing run-time dependencies\nduring parsing:\n\n::\n\n    # barpkg/bar.py\n\n    def main(app, args):\n        pass\n\nThe package can then broadcast the module ``barpkg.commands``\ncontaining the supported commands:\n\n::\n\n    [myapp.commands]\n    barpkg = barpkg.commands\n\nNow when your extension package is installed the commands will automatically\nbecome available.\n\nContext Factory\n===============\n\nEach subcommand, when executed, is passed a context object which defines a\nreusable API between subcommands. This is really the secret sauce of\n``subparse`` that makes it really easy to build your own shared CLI features.\n\nThe ``context_factory`` argument to the ``subparse.CLI`` allows for defining\nan object that is passed to all commands. This factory can also be a\ngenerator, allowing it to ``yield`` the context object and then cleanup\nafter the command is complete. For example:\n\n::\n\n    import transaction\n\n    def context_factory(cli, args):\n        tm = transaction.TransactionManager(explicit=True)\n        with tm:\n            yield tm\n\nIn the above example the transaction manager is available to all subcommands\nand it can commit/abort based on whether the command raises an exception.\n\nEach subcommand can pass custom kwargs to the context factory via the\n``context_kwargs`` argument. For example, if a single subcommand wishes to\nopt-out of the transaction manager:\n\n::\n\n    def context_factory(cli, args, without_tm=False):\n        if without_tm:\n            yield\n\n        tm = transaction.TransactionManager(explicit=True)\n        with tm:\n            yield tm\n\n    @command(..., context_kwargs=dict(without_tm=True))\n    def foo(parser):\n        \"\"\"\" Run a command without the tm enabled.\"\"\"\n\n0.6 (2022-05-15)\n================\n\n- Drop Python 2.7, 3.4, 3.5, 3.6, 3.7.\n\n- Add Python 3.8, 3.9, 3.10.\n\n- Drop dependency on pkg_resources and use importlib.metadata.\n\n- 100% test coverage.\n\n0.5.3 (2019-03-09)\n==================\n\n- Output help to ``sys.stderr`` when parsing fails.\n\n- Support passing ``context_kwargs`` to the ``command`` decorator. These\n  arguments will be passed to the ``context_factory`` when the command is\n  executed.\n\n0.5.2 (2019-03-09)\n==================\n\n- Sort subcommands in help output.\n\n0.5.1 (2019-03-08)\n==================\n\n- Use the ``argparse.RawTextHelpFormatter`` formatter class.\n\n0.5 (2019-03-08)\n================\n\n- Add Python 3.7 support.\n\n- Fix a deprecation warning coming from setuptools.\n\n- Conform more closely to PEP-257 for docstring parsing.\n\n- Modify how the help text is displayed using the\n  ``argparse.RawDescriptionHelpFormatter`` formatter class.\n\n0.4 (2018-05-03)\n================\n\n- Drop Python 2.6, 3.2 and 3.3 support.\n\n- Add Python 3.4, 3.5, 3.6 support.\n\n- Allow the ``context_factory`` to be a generator which yields the context.\n  This allows the context to wrap the full lifecycle of the CLI.\n\n0.3.3 (2013-08-12)\n==================\n\nNo functional changes from 0.3.2.\n\n- Improve documentation.\n\n0.3.2 (2013-08-06)\n==================\n\n- Add `CLI.run` API for simply executing the command line.\n\n0.3.1 (2013-08-06)\n==================\n\n- Improve the help output.\n\n0.3 (2013-08-06)\n================\n\n- Rename subcommands to commands in the API.\n\n0.2 (2013-08-06)\n================\n\n- Underscores in function names are converted to dashes in their respective\n  subcommand names.\n- Add `CLI.add_generic_options` API.\n- Add a new `help` subcommand, allowing for `myapp help foo`.\n- Allow relative imports in the subcommand specification.\n\n0.1 (2013-08-05)\n================\n\n- Initial Commits\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A command line helper library for extensible subcommands",
    "version": "0.6",
    "split_keywords": [
        "argparse",
        "cli",
        "commandline",
        "subcommand"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "1ef9970a82e918e48f596f45b6e3e693",
                "sha256": "f5bfe8ed9328b170d294f19bbac70356806802455fd671c75d0182f517fe461b"
            },
            "downloads": -1,
            "filename": "subparse-0.6-py3-none-any.whl",
            "has_sig": true,
            "md5_digest": "1ef9970a82e918e48f596f45b6e3e693",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 8811,
            "upload_time": "2022-05-15T21:11:20",
            "upload_time_iso_8601": "2022-05-15T21:11:20.344700Z",
            "url": "https://files.pythonhosted.org/packages/aa/0c/28a123892df8b62663c5ffb0a4b616b233f53dd98a29f7cf9a6c59dcef42/subparse-0.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "0aa6c90c21e7a76b2c525f09f8c8720b",
                "sha256": "619c2fd1ca9a3731182c60720b9cc2d601af7b0710834a950b78312616d940e1"
            },
            "downloads": -1,
            "filename": "subparse-0.6.tar.gz",
            "has_sig": true,
            "md5_digest": "0aa6c90c21e7a76b2c525f09f8c8720b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 14569,
            "upload_time": "2022-05-15T21:11:22",
            "upload_time_iso_8601": "2022-05-15T21:11:22.039462Z",
            "url": "https://files.pythonhosted.org/packages/6e/c8/15bbaeaf939a2925ff48a474b9790209b1829ec1edc1302137de64bd6984/subparse-0.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-05-15 21:11:22",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "mmerickel",
    "github_project": "subparse",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": false,
    "tox": true,
    "lcname": "subparse"
}
        
Elapsed time: 0.40912s