argtoolbox


Nameargtoolbox JSON
Version 1.1.5 PyPI version JSON
download
home_pagehttps://github.com/fred49/argtoolbox
SummaryThe easy way to create a short program with file options and command line options.
upload_time2023-07-16 14:02:01
maintainer
docs_urlNone
authorFrederic MARTIN
requires_python
licenseGPL3
keywords argparse configfile command line interface
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Argtoolbox
==========

Description
-----------

It helps to build a command line tool with argparse module.
It also use ConfigParser module to store default values into a
configuration file store in your profile.

It checks the data type, if it is required, etc... without repeat your
constraint once for the config file, and another time for the cli parser.
Usefull trick, data store in the configuration file can be used as the
default value of the argparse argument.

This lets you focus on the command you want to do, not the input processing
(cli or config file)

Every program build with this tool have auto complete support on options and
arguments through argcomplete module.


Installation
------------

You can install this module using : ``pip install argtoolbox``.


QuickStart : Very Basic Usage
-----------------------------

1. Imports :
~~~~~~~~~~~~

First of all, you just need the following classes to build your own script :

* **DefaultCommand :** The default class to extend in order to create your own
  command class.

* **BasicProgram :** The most simple program to run your command classes.


2. Declaration :
~~~~~~~~~~~~~~~~

There is a script called sample-program.py which contains all the following
lines of code.

1. First you have to create your command class TestCommand. (**Step 1**)
2. In the ``__call__`` method, you can do every thing you want. The first and only
   arg of this method is the args object created by Argparse.parser. (**Step 2**)
3. You create an other class MyProgram (which extends the BasicProgram) (**Step 3**)
4. Now you create your  ``argparse.parser`` and your declare your argument, option and command. (**Step 4**)
5. Finally you just have to instanciate your class MyProgram and run it. (**Step 5**).


.. code-block:: python

    #! /usr/bin/env python2
    # -*- coding: utf-8 -*-
    # PYTHON_ARGCOMPLETE_OK


    from argtoolbox import DefaultCommand
    from argtoolbox import BasicProgram

    # Step 1
    class TestCommand(DefaultCommand):
        """Just a simple command, using the default command class.
        It will print the inputs args to stdout"""

        def __call__(self, args):
            super(TestCommand, self).__call__(args)
            # Step 2
            print ""
            print "This is the beginning of the TestCommand class."
            print "The command line arguments (argv) :"
            print "-----------------------------------"
            print ""
            print "This is the end of the TestCommand class."
            print ""

    # Step 3
    class MyProgram(BasicProgram):

        def add_commands(self):
            # Step 4
            subparsers = self.parser.add_subparsers()
            parser_tmp = subparsers.add_parser(
                'test',
                help="This command will print cli argv and configuration read \
                from the config file.")
            parser_tmp.add_argument('--host', required=True)
            parser_tmp.add_argument('--port', default=3000)
            parser_tmp.set_defaults(__func__=TestCommand(self.config))


    # Step 5
    if __name__ == "__main__":

        PROG = MyProgram("sample-program",
                            desc="""Just a description for a sample program.""")
        PROG()



3. Utilisation :
~~~~~~~~~~~~~~~~

Now you can show the help menu using the following command :

``$ ./sample-program.py test -h``

**Console ouput :**

.. code-block:: python

    usage: sample-program test [-h] --host HOST [--port PORT]

    optional arguments:
      -h, --help   show this help message and exit
      --host HOST
      --port PORT

Or run your command :

``$  ./sample-program.py test --host 127.0.0.1``

**Console ouput :**

.. code-block:: python

    This is the beginning of the TestCommand class.
    The command line arguments (argv) :
    -----------------------------------
    Namespace(__func__=<__main__.TestCommand object at 0xb721a92c>,
    config_file=None, host='127.0.0.1', port=3000, verbose=False)

    This is the end of the TestCommand class.

You can see the variable ``host`` contains the input message ``127.0.0.1`` into the
args object.
The option ``port`` contains the default value ``3000``.


Advanced usage
--------------

At this point, this program does not do much more than the argparse module can
do.
In the cas you have a lot of command and option, it could be usefull to store
default values in a configuration file like ``sample-program.cfg``


4. Imports :
~~~~~~~~~~~~

First of all, you just need the following classes to build your own script :

* **TestCommand :** This command class will print to stdout the inputs args and
  the configuration file content.

* **BasicProgram :** The most simple program to run your command classes.

* **SimpleSection :** This class is used to declare a Section in the config file
  (ConfigFile)

* **Element :** This class is used to declare an Option (a field) in the
  previous section.

* **Base64ElementHook :** This hook is used as a post reading processing in
  order to convert base64 data stored into the config file into plain text data.



5. Declaration :
~~~~~~~~~~~~~~~~

There is a script called sample-program2.py which contains all the following
lines of code.


#. Instead of creating a config file, we will use an in-memory config file
   (**Step 1**)
#. You create an other class MyProgram (which extends the BasicProgram) (**Step
   2**)
#. We override the default method called ``add_config_options``. (**Step 3**)
#. We declare the section named ``ldap`` that we are looking for.
#. We declare all the fields store into the previous section. For each fied, you can says if it is required, the default value, the type, an optional description. See the documentatino for more details. (**Step 5**).
#. The we declare all argparse arguments using the previous configuration declaration. This is very usefull because the data store into the configuration file are used as the default value for the argparse argument. The description, the type, required or not, ... declared in the ``add_config_options`` method are used to configure the parser argument. No need to repeat your self. (**Step 6**)
#. Declaration of the ``test`` argument using TestCommand class. (**Step 7**)
#. Finally you just have to instanciate your class MyProgram, the first argument is the program name. (**Step 8**)
#. We override the default config file name ``'.<program name>.cfg'``. (**Step 9**)
#. We launch the program. (**Step 10**)


.. code-block:: python

    #! /usr/bin/env python2
    # -*- coding: utf-8 -*-
    # PYTHON_ARGCOMPLETE_OK

    import io
    from argtoolbox import TestCommand
    from argtoolbox import BasicProgram
    from argtoolbox import SimpleSection, Element, Base64ElementHook

    # Step 1
    SAMPLE_CONFIG = """
    [ldap]

    host=127.0.0.1
    port=389
    suffix=dc=nodomain
    account=cn=admin,dc=nodomain
    password=toto

    \n"""

    # Step 2
    class MyProgram(BasicProgram):

        # Step 3
        def add_config_options(self):
            # Step 4
            # section ldap
            section_ldap = self.config.add_section(SimpleSection("ldap"))
            # Step 5
            section_ldap.add_element(Element('debug',
                                             e_type=int,
                                             default=0,
                                             desc="""debug level : default : 0."""))
            section_ldap.add_element(Element('host',
                                             required=True,
                                             default="192.168.1.1"))
            section_ldap.add_element(Element('account', required=True))
            section_ldap.add_element(Element('port', e_type=int))
            section_ldap.add_element(Element('password',
                                             required=True,
                                             hidden=True,
                                             desc="account password to ldap",
                                             hooks=[Base64ElementHook(), ]))

       def add_commands(self):
            # Step 6
            self.parser.add_argument(
                '--host', **self.config.ldap.host.get_arg_parse_arguments())
            self.parser.add_argument(
                '--port', **self.config.ldap.port.get_arg_parse_arguments())
            self.parser.add_argument(
                '-d',
                action="count",
                **self.config.ldap.debug.get_arg_parse_arguments())

            # Step 7
            subparsers = self.parser.add_subparsers()
            parser_tmp = subparsers.add_parser(
                'test',
                help="This simple command print cli argv and configuration read \
                form config file.")
            parser_tmp.set_defaults(__func__=TestCommand(self.config))


    if __name__ ≡ "__main__":

        # Step 8
        PROG = MyProgram("sample-program",
            # Step 9
                         config_file=io.BytesIO(SAMPLE_CONFIG),
                         desc="""Just a description for a sample program.""")
        # Step 10
        PROG()

6. Utilisation :
~~~~~~~~~~~~~~~~

Now you can run your command :

``$ ./sample-program2.py --host an.other.host.com test``

**Console ouput :**

.. code-block:: python

    This is the beginning of the TestCommand class.

    The loaded configuration :
    ---------------------------
    Configuration of sample-program :

            Section LDAP
             - debug : 0
             - host : 127.0.0.1
             - account : cn=admin,dc=nodomain
             - port : 389
             - password : xxxxxxxx


    The command line arguments (argv) :
    ------------------------------------
    Namespace(__func__=<argtoolbox.argtoolbox.TestCommand object at 0xb7199f8c>, config_file=None, debug=0, host='an.other.host.com', port=389, verbose=False)

    This is the end of the TestCommand class.

You can see the variable ``host`` contains the input message ``an.other.host.com`` into the
args object. The option ``port`` contains the default value ``389``.
You can also acces to the values store into the configuration file like ``account`` or ``password`` which can not be override by the CLI.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/fred49/argtoolbox",
    "name": "argtoolbox",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "argparse ConfigFile command line interface",
    "author": "Frederic MARTIN",
    "author_email": "frederic.martin.fma@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/6b/ba/39c952ab8a813558197049eecf6cce89351d9f6c166585eda1d0f1e5ed69/argtoolbox-1.1.5.tar.gz",
    "platform": null,
    "description": "Argtoolbox\n==========\n\nDescription\n-----------\n\nIt helps to build a command line tool with argparse module.\nIt also use ConfigParser module to store default values into a\nconfiguration file store in your profile.\n\nIt checks the data type, if it is required, etc... without repeat your\nconstraint once for the config file, and another time for the cli parser.\nUsefull trick, data store in the configuration file can be used as the\ndefault value of the argparse argument.\n\nThis lets you focus on the command you want to do, not the input processing\n(cli or config file)\n\nEvery program build with this tool have auto complete support on options and\narguments through argcomplete module.\n\n\nInstallation\n------------\n\nYou can install this module using : ``pip install argtoolbox``.\n\n\nQuickStart : Very Basic Usage\n-----------------------------\n\n1. Imports :\n~~~~~~~~~~~~\n\nFirst of all, you just need the following classes to build your own script :\n\n* **DefaultCommand :** The default class to extend in order to create your own\n  command class.\n\n* **BasicProgram :** The most simple program to run your command classes.\n\n\n2. Declaration :\n~~~~~~~~~~~~~~~~\n\nThere is a script called sample-program.py which contains all the following\nlines of code.\n\n1. First you have to create your command class TestCommand. (**Step 1**)\n2. In the ``__call__`` method, you can do every thing you want. The first and only\n   arg of this method is the args object created by Argparse.parser. (**Step 2**)\n3. You create an other class MyProgram (which extends the BasicProgram) (**Step 3**)\n4. Now you create your  ``argparse.parser`` and your declare your argument, option and command. (**Step 4**)\n5. Finally you just have to instanciate your class MyProgram and run it. (**Step 5**).\n\n\n.. code-block:: python\n\n    #! /usr/bin/env python2\n    # -*- coding: utf-8 -*-\n    # PYTHON_ARGCOMPLETE_OK\n\n\n    from argtoolbox import DefaultCommand\n    from argtoolbox import BasicProgram\n\n    # Step 1\n    class TestCommand(DefaultCommand):\n        \"\"\"Just a simple command, using the default command class.\n        It will print the inputs args to stdout\"\"\"\n\n        def __call__(self, args):\n            super(TestCommand, self).__call__(args)\n            # Step 2\n            print \"\"\n            print \"This is the beginning of the TestCommand class.\"\n            print \"The command line arguments (argv) :\"\n            print \"-----------------------------------\"\n            print \"\"\n            print \"This is the end of the TestCommand class.\"\n            print \"\"\n\n    # Step 3\n    class MyProgram(BasicProgram):\n\n        def add_commands(self):\n            # Step 4\n            subparsers = self.parser.add_subparsers()\n            parser_tmp = subparsers.add_parser(\n                'test',\n                help=\"This command will print cli argv and configuration read \\\n                from the config file.\")\n            parser_tmp.add_argument('--host', required=True)\n            parser_tmp.add_argument('--port', default=3000)\n            parser_tmp.set_defaults(__func__=TestCommand(self.config))\n\n\n    # Step 5\n    if __name__ == \"__main__\":\n\n        PROG = MyProgram(\"sample-program\",\n                            desc=\"\"\"Just a description for a sample program.\"\"\")\n        PROG()\n\n\n\n3. Utilisation :\n~~~~~~~~~~~~~~~~\n\nNow you can show the help menu using the following command :\n\n``$ ./sample-program.py test -h``\n\n**Console ouput :**\n\n.. code-block:: python\n\n    usage: sample-program test [-h] --host HOST [--port PORT]\n\n    optional arguments:\n      -h, --help   show this help message and exit\n      --host HOST\n      --port PORT\n\nOr run your command :\n\n``$  ./sample-program.py test --host 127.0.0.1``\n\n**Console ouput :**\n\n.. code-block:: python\n\n    This is the beginning of the TestCommand class.\n    The command line arguments (argv) :\n    -----------------------------------\n    Namespace(__func__=<__main__.TestCommand object at 0xb721a92c>,\n    config_file=None, host='127.0.0.1', port=3000, verbose=False)\n\n    This is the end of the TestCommand class.\n\nYou can see the variable ``host`` contains the input message ``127.0.0.1`` into the\nargs object.\nThe option ``port`` contains the default value ``3000``.\n\n\nAdvanced usage\n--------------\n\nAt this point, this program does not do much more than the argparse module can\ndo.\nIn the cas you have a lot of command and option, it could be usefull to store\ndefault values in a configuration file like ``sample-program.cfg``\n\n\n4. Imports :\n~~~~~~~~~~~~\n\nFirst of all, you just need the following classes to build your own script :\n\n* **TestCommand :** This command class will print to stdout the inputs args and\n  the configuration file content.\n\n* **BasicProgram :** The most simple program to run your command classes.\n\n* **SimpleSection :** This class is used to declare a Section in the config file\n  (ConfigFile)\n\n* **Element :** This class is used to declare an Option (a field) in the\n  previous section.\n\n* **Base64ElementHook :** This hook is used as a post reading processing in\n  order to convert base64 data stored into the config file into plain text data.\n\n\n\n5. Declaration :\n~~~~~~~~~~~~~~~~\n\nThere is a script called sample-program2.py which contains all the following\nlines of code.\n\n\n#. Instead of creating a config file, we will use an in-memory config file\n   (**Step 1**)\n#. You create an other class MyProgram (which extends the BasicProgram) (**Step\n   2**)\n#. We override the default method called ``add_config_options``. (**Step 3**)\n#. We declare the section named ``ldap`` that we are looking for.\n#. We declare all the fields store into the previous section. For each fied, you can says if it is required, the default value, the type, an optional description. See the documentatino for more details. (**Step 5**).\n#. The we declare all argparse arguments using the previous configuration declaration. This is very usefull because the data store into the configuration file are used as the default value for the argparse argument. The description, the type, required or not, ... declared in the ``add_config_options`` method are used to configure the parser argument. No need to repeat your self. (**Step 6**)\n#. Declaration of the ``test`` argument using TestCommand class. (**Step 7**)\n#. Finally you just have to instanciate your class MyProgram, the first argument is the program name. (**Step 8**)\n#. We override the default config file name ``'.<program name>.cfg'``. (**Step 9**)\n#. We launch the program. (**Step 10**)\n\n\n.. code-block:: python\n\n    #! /usr/bin/env python2\n    # -*- coding: utf-8 -*-\n    # PYTHON_ARGCOMPLETE_OK\n\n    import io\n    from argtoolbox import TestCommand\n    from argtoolbox import BasicProgram\n    from argtoolbox import SimpleSection, Element, Base64ElementHook\n\n    # Step 1\n    SAMPLE_CONFIG = \"\"\"\n    [ldap]\n\n    host=127.0.0.1\n    port=389\n    suffix=dc=nodomain\n    account=cn=admin,dc=nodomain\n    password=toto\n\n    \\n\"\"\"\n\n    # Step 2\n    class MyProgram(BasicProgram):\n\n        # Step 3\n        def add_config_options(self):\n            # Step 4\n            # section ldap\n            section_ldap = self.config.add_section(SimpleSection(\"ldap\"))\n            # Step 5\n            section_ldap.add_element(Element('debug',\n                                             e_type=int,\n                                             default=0,\n                                             desc=\"\"\"debug level : default : 0.\"\"\"))\n            section_ldap.add_element(Element('host',\n                                             required=True,\n                                             default=\"192.168.1.1\"))\n            section_ldap.add_element(Element('account', required=True))\n            section_ldap.add_element(Element('port', e_type=int))\n            section_ldap.add_element(Element('password',\n                                             required=True,\n                                             hidden=True,\n                                             desc=\"account password to ldap\",\n                                             hooks=[Base64ElementHook(), ]))\n\n       def add_commands(self):\n            # Step 6\n            self.parser.add_argument(\n                '--host', **self.config.ldap.host.get_arg_parse_arguments())\n            self.parser.add_argument(\n                '--port', **self.config.ldap.port.get_arg_parse_arguments())\n            self.parser.add_argument(\n                '-d',\n                action=\"count\",\n                **self.config.ldap.debug.get_arg_parse_arguments())\n\n            # Step 7\n            subparsers = self.parser.add_subparsers()\n            parser_tmp = subparsers.add_parser(\n                'test',\n                help=\"This simple command print cli argv and configuration read \\\n                form config file.\")\n            parser_tmp.set_defaults(__func__=TestCommand(self.config))\n\n\n    if __name__ \u2261 \"__main__\":\n\n        # Step 8\n        PROG = MyProgram(\"sample-program\",\n            # Step 9\n                         config_file=io.BytesIO(SAMPLE_CONFIG),\n                         desc=\"\"\"Just a description for a sample program.\"\"\")\n        # Step 10\n        PROG()\n\n6. Utilisation :\n~~~~~~~~~~~~~~~~\n\nNow you can run your command :\n\n``$ ./sample-program2.py --host an.other.host.com test``\n\n**Console ouput :**\n\n.. code-block:: python\n\n    This is the beginning of the TestCommand class.\n\n    The loaded configuration :\n    ---------------------------\n    Configuration of sample-program :\n\n            Section LDAP\n             - debug : 0\n             - host : 127.0.0.1\n             - account : cn=admin,dc=nodomain\n             - port : 389\n             - password : xxxxxxxx\n\n\n    The command line arguments (argv) :\n    ------------------------------------\n    Namespace(__func__=<argtoolbox.argtoolbox.TestCommand object at 0xb7199f8c>, config_file=None, debug=0, host='an.other.host.com', port=389, verbose=False)\n\n    This is the end of the TestCommand class.\n\nYou can see the variable ``host`` contains the input message ``an.other.host.com`` into the\nargs object. The option ``port`` contains the default value ``389``.\nYou can also acces to the values store into the configuration file like ``account`` or ``password`` which can not be override by the CLI.\n",
    "bugtrack_url": null,
    "license": "GPL3",
    "summary": "The easy way to create a short program with file options and command line options.",
    "version": "1.1.5",
    "project_urls": {
        "Homepage": "https://github.com/fred49/argtoolbox"
    },
    "split_keywords": [
        "argparse",
        "configfile",
        "command",
        "line",
        "interface"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6bba39c952ab8a813558197049eecf6cce89351d9f6c166585eda1d0f1e5ed69",
                "md5": "a69bf1ce74d274be51d50f54870f1ad7",
                "sha256": "f277b8bce1b4132ea1dddccb733ef6470a5b86e5aa2ac43f2e741dcf7e89f938"
            },
            "downloads": -1,
            "filename": "argtoolbox-1.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "a69bf1ce74d274be51d50f54870f1ad7",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 37153,
            "upload_time": "2023-07-16T14:02:01",
            "upload_time_iso_8601": "2023-07-16T14:02:01.725993Z",
            "url": "https://files.pythonhosted.org/packages/6b/ba/39c952ab8a813558197049eecf6cce89351d9f6c166585eda1d0f1e5ed69/argtoolbox-1.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-16 14:02:01",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "fred49",
    "github_project": "argtoolbox",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "argtoolbox"
}
        
Elapsed time: 0.08878s