module cli.cli_helper

Short summary

module pyquickhelper.cli.cli_helper

Automate the creation of a parser based on a function.

source on GitHub

Functions

function

truncated documentation

call_cli_function

Calls a function f given parsed arguments.

call_gui_function

Opens a GUI based on tkinter which allows the user to run a command line through a windows. The function …

clean_documentation_for_cli

Cleans the documentation before integrating into a command line documentation.

cli_main_helper

Implements the main commmand line for a module.

create_cli_argument

Adds an argument for argparse.ArgumentParser.

create_cli_parser

Automatically creates a parser based on a function, its signature with annotation and its documentation (assuming …

guess_module_name

Guesses the module name based on a function.

Documentation

Automate the creation of a parser based on a function.

source on GitHub

pyquickhelper.cli.cli_helper.call_cli_function(f, args=None, parser=None, fLOG=<built-in function print>, skip_parameters=('fLOG', ), cleandoc=('epkg', 'link'), prog=None, **options)[source]

Calls a function f given parsed arguments.

Parameters:
  • f – function to call

  • args – arguments to parse (if None, it considers sys.argv)

  • parser – parser (can be None, in that case, create_cli_parser is called)

  • fLOG – logging function

  • skip_parameters – see create_cli_parser

  • cleandoc – cleans the documentation before converting it into text, clean_documentation_for_cli

  • prog – to give the parser a different name than the function name

  • options – additional Sphinx options

Returns:

the output of the wrapped function

This function is used in command line pyq_sync. Its code can can be used as an example. The command line can be tested as:

class TextMyCommandLine(unittest.TestCase):

    def test_mycommand_line_help(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        rows = []

        def flog(*l):
            rows.append(l)

        mycommand_line(args=['-h'], fLOG=flog)

        r = rows[0][0]
        if not r.startswith("usage: mycommand_line ..."):
            raise RuntimeError(r)

source on GitHub

pyquickhelper.cli.cli_helper.call_gui_function(dfct, fLOG=<built-in function print>, utest=False)[source]

Opens a GUI based on tkinter which allows the user to run a command line through a windows. The function requires tkinterquickhelper.

Parameters:
  • dfct – dictionary { key: fct }

  • args – arguments

  • utest – for unit test purposes, does not start the main loop if True

This GUI can be triggered with the following command line:

python -m <module> --GUI

If one of your function prints out some information or raises an exception, option -u should be added:

python -u -m <module> --GUI

source on GitHub

pyquickhelper.cli.cli_helper.clean_documentation_for_cli(doc, cleandoc)[source]

Cleans the documentation before integrating into a command line documentation.

Parameters:
  • doc – documentation

  • cleandoc – a string which tells how to clean, or a function which takes a function and returns a string

The function removes everything after .. cmdref:: and .. cmdreflist as it creates an infinite loop of processus if this command is part of the documentation of the command line itself.

source on GitHub

pyquickhelper.cli.cli_helper.cli_main_helper(dfct, args, fLOG=<built-in function print>)[source]

Implements the main commmand line for a module.

Parameters:
  • dfct – dictionary { key: fct }

  • args – arguments

  • fLOG – logging function

Returns:

the output of the wrapped function

The function makes it quite simple to write a file __main__.py which implements the syntax python -m <module> <command> <arguments>. Here is an example of implementation based on this function:

import sys


def main(args, fLOG=print):
    '''
    Implements ``python -m pyquickhelper <command> <args>``.

    :param      args:        command line arguments
    :param      fLOG:        logging function
    '''
    try:
        from .pandashelper import df2rst
        from .pycode import clean_files
        from .cli import cli_main_helper
    except ImportError:
        from pyquickhelper.pandashelper import df2rst
        from pyquickhelper.pycode import clean_files
        from pyquickhelper.cli import cli_main_helper

    fcts = dict(df2rst=df2rst, clean_files=clean_files)
    cli_main_helper(fcts, args=args, fLOG=fLOG)


if __name__ == "__main__":
    main(sys.argv[1:])

The function takes care of the parsing of the command line by leveraging the signature and the documentation of the function if its docstring is written in rst format. For example, function clean_files is automatically wrapped with function call_cli_function. The command python -m pyquickhelper clean_files --help produces the following output:

Clean files

The command line cleans files in a folder.

<<<

python -m pyquickhelper clean_files --help

>>>

usage: clean_files [-h] [-f FOLDER] [-p POSREG] [-n NEGREG] [--op OP]

Cleans ``\r`` in files a folder and subfolders with a given extensions.
Backslashes are replaces by ``/``. The regular expressions applies on the
relative path starting from *folder*.

optional arguments:
  -h, --help            show this help message and exit
  -f FOLDER, --folder FOLDER
                        folder to clean (default: .)
  -p POSREG, --posreg POSREG
                        regular expression to select files to process
                        (default: .*[.]((py)|(rst))$)
  -n NEGREG, --negreg NEGREG
                        regular expression to skip files to process (default:
                        .*[.]git/.*)
  --op OP               kind of cleaning to do, options are CR, CRB, pep8, see
                        below for more details (default: CR)

The command line can be replaced by a GUI triggered with the following command line. It relies on module :epkg`tkinterquickhelper`. See call_gui_function.

python -u -m <module> --GUI

source on GitHub

pyquickhelper.cli.cli_helper.create_cli_argument(parser, param, doc, names, positional)[source]

Adds an argument for argparse.ArgumentParser.

Parameters:
  • parserargparse.ArgumentParser

  • param – parameter (from the signature)

  • doc – documentation for this parameter

  • names – for shortnames

  • positional – positional arguments

If an annotation offers mutiple types, the first one will be used for the command line.

source on GitHub

pyquickhelper.cli.cli_helper.create_cli_parser(f, prog=None, layout='sphinx', skip_parameters=('fLOG',), cleandoc=('epkg', 'link'), positional=None, cls=None, **options)[source]

Automatically creates a parser based on a function, its signature with annotation and its documentation (assuming this documentation is written using Sphinx syntax).

Parameters:
  • f – function

  • prog – to give the parser a different name than the function name

  • use_sphinx – simple documentation only requires docutils, richer requires sphinx

  • skip_parameters – do not expose these parameters

  • cleandoc – cleans the documentation before converting it into text, clean_documentation_for_cli

  • options – additional Sphinx options

  • positional – positional argument

  • cls – parser class, argparse.ArgumentParser by default

Returns:

argparse.ArgumentParser

If an annotation offers mutiple types, the first one will be used for the command line.

source on GitHub

pyquickhelper.cli.cli_helper.guess_module_name(fct)[source]

Guesses the module name based on a function.

Parameters:

fct – function

Returns:

module name

source on GitHub