welcome to sphinxcontrib-argdoc

Introduction

sphinxcontrib.argdoc is an extension for the Sphinx documentation engine.

It automatically generates tables describing command-line arguments for executable scripts written in Python, and inserts those tables into the scripts’ :automodule: documentation. The only requirements are:

  1. The exectuable scripts use the Python argparse module for argument parsing
  2. The rst stub files for the scripts include the :automodule: directive (which they will, by default, if you use sphinx-apidoc).

To start using sphinxcontrib.argdoc, see the Quickstart guide.

To view the source code, check out the sphinx-contrib repository on BitBucket.

Indices and tables

Quickstart

Installation

Install stable versions via pip. For a single-user installation:

$ pip install --user sphinxcontrib-argdoc

For a system-wide installation:

$ sudo pip install sphinxcontrib-argdoc

Using sphinxcontrib.argdoc in your project

Setting up sphinxcontrib.argdoc only takes a few steps:

  1. Find the extensions definition in your Sphinx configuration file, conf.py, and add ‘sphinxcontrib.argdoc’ to the list. For example:

    # inside conf.py
    extensions = [
        'sphinx.ext.autodoc',
        'sphinx.ext.autosummary',
        'sphinx.ext.intersphinx',
        'sphinxcontrib.argdoc' # <---- ta-da!
    ]
    
  2. Generate document stubs for your package. It is easiest to use sphinx-apidoc. From the terminal:

    $ cd my_project_folder/my_package_folder
    $ sphinx-apidoc -e -o docs/source/generated my_package_name
    

    Or you can make your document stubs manually. Just make sure the final document stubs for your executable scripts include the .. automodule : directive. A stub file for a demo script (e.g. demo.rst) might look like this:

    `argdoc` demo script
    ====================
    
     .. automodule:: some_package.some_module
        :members:
        :undoc-members:
        :show-inheritance:
    
    
     .. toctree::
        :maxdepth: 2
    
  3. Make sure your executable scripts:

    1. use ArgumentParser rather than OptionParser or getopt for argument parsing
    2. contain a main-like function (typically called main) that is called when the script is executed from the shell.

    If you want your documentation to be extra nice, write a user-friendly description of your script in its module docstring, and pass the docstring contents as a description to your ArgumentParser. For example:

    #!/usr/bin/env python
    """This is my module docstring, which describes what my script does
    at length, so that users can figure out what it does. Conveniently
    this text is used both by argparse as help text in the shell, and
    by Sphinx when generating HTML documentation.
    """
    import argparse
    
    # other functions et c here
    pass
    
    def main():
        """This is the body of the program"""
        my_parser = argparse.ArgumentParser(description=__doc__,
                                            formatter_class=argparse.RawDescriptionHelpFormatter)
        my_parser.add_argument("some_arg",type=str,help="some helptext, if you want")
        my_parser.add_argument("--some_keyword",type=int,help="Some other helptext")
        # et c. other options & program body
    
        args = argparse.parse_args()
    
        # rest of main()
        pass
    
    if __name__ == "__main__":
        main()
    

    That’s it! There is nothing else you need to do. For further info or configuration options, see Advanced usage. For examples, see Examples.

Warning

sphinxcontrib.argdoc generates its documentation by calling your executable scripts with the argument --help. Therefore, any side effects caused by executing your script will take effect during the documentation build process.

Advanced usage

Preventing sphinxcontrib-argdoc from processing one or more, but not all scripts, in a package

To prevent sphinxcontrib.argdoc from processing a main-like function, in one of the executable scripts in your package, use the noargdoc() function decorator. For example:

#!/usr/bin/env python
import argparse
from sphinxcontrib.argdoc import noargdoc

@noargdoc
def main():
    """Main-like function that would normally be processed by
    `sphinxcontrib-argdoc` but that will instead be skipped!
    """
    # main function body here
    parser = argparse.ArgumentParser()
    pass

if __name__ == "__main__":
    main()

Processing a main-like function named something other than main

If your code conventions use a name different from main for main-like functions, sphinxcontrib.argdoc can still process these. Just set the value of the configuration parameter argdoc_main_func to your function name in conf.py:

...

# somewhere in conf.py
argdoc_main_func = "whatever_we_call_main_funcs_at_our_organization"

...

Using alternate prefix characters in your ArgumentParser

If your executable script uses one or more alternate prefix characters (e.g. ‘+’ instead of or in addition to ‘-‘, set the configuration parameter argdoc_prefix_chars to a string containing all of the prefix characters used by all of your scripts in your conf.py:

# somewhere in conf.py
argdoc_prefix_chars = "-+" # our scripts use both '-' and '+' to prefix optional arguments

Debugging sphinxcontrib.argdoc output

To save a snapshot of the raw reStructuredText generated by argdoc for each file after processing, set argdoc_save_rst to True in your conf.py. In your build folder, you will find files names X_postargdoc.rst where X corresponds to the name of the rst stub file.

Frequently-asked questions

Is there, or will there be, support for optparse?
Because optparse was deprecated in Python 2.7, we have no plans to support it at present. If you’d still like to use sphinxcontrib.argdoc, see the Python documentation on upgrading optparse code.
My main-like function is not named main. Can I use sphinxcontrib.argdoc without changing the function name?
Absolutely. Just set argdoc_main_func to the name of your function (as a string) in conf.py. See Processing a main-like function named something other than main for instructions.
My executable scripts use alternate prefix characters.
Can sphinxcontrib.argdoc handle these? Yes. See Using alternate prefix characters in your ArgumentParser for details.
Does sphinxcontrib.argdoc support subcommands?
Yes. You don’t need to do anything special. sphinxcontrib.argdoc will find these all by itself.
Does sphinxcontrib.argdoc support nested subcommands?
Yes. See the Examples.

Glossary of terms

argument
Terms or options that control or modify a function or script’s behavior.
docstring
Documentation for a Python function, method, class, module, or object. These must appear as triple-quoted strings immediately below the def line for functions and methods, and immediately below the class line for classes. module docstrings appear immediately at the top of the module.
executable scripts
Scripts that can be executed from a shell, as opposed to (or in addition to) inside the Python interpreter.
main-like function

A function that is called when a script is executed from a shell, as opposed to inside an interactive Python session. These are the functions from whose arguments sphinxcontrib.argdoc generates documentation.

These are typically named main, and in idiomatically written Python are called by the following lines, which appear as the final lines of executable scripts:

if __name__ == "__main__":
    main()

sphinxcontrib.argdoc detects main-like functions by scanning modules for functions whose names match the current value of the configuration parameter argdoc_main_func (set in conf.py, with default value ‘main’).

module docstring

Documentation for a Python module, which appears as a triple-quoted string starting on the first code line:

#!/usr/bin/env python
"""This is the module docstring. It can be very long
and span multiple lines, contain tables, et c
"""

import argparse
...
shell
An environment that executes commands. This could be a command-line environment like the bash prompt, or a graphical environment like the OSX Finder.

Contributing

We welcome contributions! But we are new at this, so please be patient. Right now, we follow these conventions:

Workflow

  1. Testing: This is a pretty low-key project, but we will not accept feature additions without companion tests. Tests should be written using nose or Python’s unittest framework. And, if you submit patches without adding new features, please make sure all tests in the current test suite still pass. See sphinxcontrib.argdoc.test.test_argdoc for details on how tests are structured.
  2. Our main repository is at http://bitbucket.org/birkenfeld/sphinx-contrib . To submit a patch, fork the repository and submit a pull request.

Formatting

  1. Code formatting: Code should be formatted as described in PEP8, noting that we use four spaces for indentation.

  2. Docstrings and documentation: These should be formatted for Sphinx, as described in the numpy documentation guide with guidance from PEP257. This means that docstrings are formatted in reStructuredText.

    Beyond that:

    • If you use technical terms, please check if a synonym of your term is already defined in the glossary, and then use that.

      If no synonym is present, please add your term to the glossary, and refer to it using the :term: directive.

    • Rather than define links inline, please put them in docs/source/links.txt.

    • Use four-space indentation in rst files as well as in source

    • Refer to files using fixed-width formatting e.g. ‘``fixed-width``’

License

sphincontrib.argdoc is published under the BSD 3-Clause license, which is as follows:

The BSD 3-Clause License

Copyright (c) 2015, Joshua Griffin Dunn All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name of this package nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

sphinxcontrib.argdoc package

Extension for the Sphinx documentation engine. Programatically generates tables describing command-line arguments for Python modules that use ArgumentParser to parse arguments. These tables are then inserted into descriptions generated by the :automodule: directive used by the Sphinx autodoc extension.

sphinxcontrib.argdoc.setup(app)[source]

Set up sphinxcontrib.argdoc extension and register it with Sphinx

Parameters:

app

Sphinx application instance

Submodules

sphinxcontrib.argdoc.ext module

Functions that constitute the sphinxcontrib.argdoc extension for Sphinx.

User functions

noargdoc()
Function decorator that forces sphinxcontrib.argdoc to skip a main-like function it would normally process

Developer functions

format_argparser_as_docstring()
Extract tables of arguments from an ArgumentParser and from all of its subprograms, then format their descriptions and help text.
get_subcommand_tables()
Extract tables from all subcommand ArgumentParsers contained by an enclosing ArgumentParser
post_process_automodule()
Event handler that activates sphinxcontrib.argdoc upon autodoc-process-docstring events
setup()
Register sphinxcontrib.argdoc with the running Sphinx instance
sphinxcontrib.argdoc.ext.safeunicode(inp)[source]

Convert a string to unicode in a Python 2.7/3.x-safe way

Parameters:

inp : str

Input string

Returns:

unicode (Python 2.7) or string (Python 3.x)

utf-8 encoded representation of inp

sphinxcontrib.argdoc.ext.get_patterns(prefix_chars='-')[source]

Retrieve a dictionary of regular expressions that separate argument names from their values and descriptions

Parameters:

prefix_chars : str, optional

String of prefix characters that the ArgumentParser uses (Default: ‘-‘)

Returns:

dict

Dictionary of regular expression patterns

sphinxcontrib.argdoc.ext.get_col1_text(matchdict)[source]

Format argument name(s) and value(s) for column 1 of argument tables

Parameters:

matchdict : dict

Dictionary of values

Returns:

str (unicode if Python 2.7)

sphinxcontrib.argdoc.ext.get_col2_text(matchdict)[source]

Format argument descriptions, if present, for column 2 of argument tables

Parameters:

matchdict : dict

Dictionary of values

Returns:

str (unicode if Python 2.7)

sphinxcontrib.argdoc.ext.make_rest_table(rows, title=False, indent=0)[source]

Make a reStructuredText table from a list of rows of items

Parameters:

rows : list of tuples

A row of text to put in the table, each tuple item a cell

title : bool, optional

If True, the first pair is assumed to contain column headings (Default: False)

indent_size : int, optional

Number of spaces prepend to each line of output (Default: 0)

Returns:

list

List of strings, corresponding to multi-line reStructuredText table

sphinxcontrib.argdoc.ext.format_warning(topline, details)[source]

Format warning text clearly

Parameters:

topline : str

One-line description of warning

details : str

Multiline, detailed description of warning (e.g. exception info)

Returns:

str

Multiline warning message, formatted

sphinxcontrib.argdoc.ext.noargdoc(func)[source]

Decorator that forces sphinxcontrib.argdoc to skip processing of func

Parameters:

func : function

main-like function of a script

Returns:

func

wrapped function

sphinxcontrib.argdoc.ext.get_subcommand_tables(app, obj, help_lines, patterns, start_line, command_chain='', section_head=True, header_level=1)[source]

Process help output from an ArgumentParser that includes one or more subcommands. Called by format_argparser_as_docstring()

Parameters:

app

Sphinx application instance

obj : object

Object (e.g. module, class, function) to document

help_lines : list

List of strings, each corresponding to a line of output from having passed --help as an argument to the main-like function

patterns : dict

Dictionary names of line types in argparse output to regular expression patterns that process those line types

start_line : int

Line in argparse help output containing subcommand header

section_head : bool, optional

If True, a section header for “Command-line arguments” will be included in the output. (Default: True)

pre_args : int, optional

Number of arguments required to be supplied before subcommand help can be retrieved (Default: 0)

header_level : int, optional

Level of header to use for section_name. Lower numbers are higher precedence. (Default: 1)

Returns:

list

List of strings encoding reStructuredText table of command-line arguments for all subprograms in the containing argparser

sphinxcontrib.argdoc.ext.format_argparser_as_docstring(app, obj, help_lines, patterns, section_head=True, section_name=u'Command-line arguments', header_level=1, _is_subcommand=False, command_chain='')[source]

Process help output from an argparse.ArgumentParser. Called by post_process_automodule() and get_subcommand_tables()

Parameters:

app

Sphinx application instance

obj : object

Object (e.g. module, class, function) to document

help_lines : list

List of strings, each corresponding to a line of output from having passed --help as an argument to the main-like function

patterns : dict

Dictionary names of line types in argparse output to regular expression patterns that process those line types

section_head : bool, optional

If True, a section header for “Command-line arguments” will be included. This messes up parsing for function docstrings, but is fine for module docstrings (Default: False).

section_name : str, optional

A name or title for the current program or subcommand. (Default: ‘Command-line arguments’)

header_level : int, optional

Level of header to use for section_name. Lower numbers are higher precedence. (Default: 1)

_is_subcommand : bool, optional

If True, include module docstring in output. Required for subcommands whose help won’t be included by in the module docstring found by autodoc. (Default: False)

Returns:

list

List of strings encoding reStructuredText table of arguments for program or subprogram

sphinxcontrib.argdoc.ext.post_process_automodule(app, what, name, obj, options, lines)[source]

Insert a table listing and describing an executable script’s command-line arguments into its :automodule: documentation.

Any main-like function decorated with the noargdoc() decorator will be skipped. A function is determined to be a main-like function if its name matches the name set in the configuration option argdoc_main_func inside conf.py. The default value for argdoc_main_func is main.

Parameters:

app

Sphinx application instance

what : str

Type of object (e.g. “module”, “function”, “class”)

name : str

Fully-qualified name of object

obj : object

Object (e.g. module, class, function) to document

options : object

Options given to the directive, whose boolean properties are set to True if their corresponding flag was given in the directive

lines : list

List of strings encoding the module docstrings after Sphinx processing

Raises:

:class:`~sphinx.errors.ConfigError`

If argdoc_main_func is defined in conf.py and is not a str

Notes

Per the autodoc spec, this function modifies lines in place.

Subpackages

sphinxcontrib.argdoc.test package

Test suites and test data for sphinxcontrib.argdoc

sphinxcontrib.argdoc.test.test_argdoc
Tests for the argdoc Sphinx extension sphinxcontrib.argdoc. All tests are implemented in here. The module docstring for sphinxcontrib.argdoc.test.test_argdoc contains information on how to add new test cases.
sphinxcontrib.argdoc.test.cases
executable scripts used as test cases for sphinxcontrib.argdoc
sphinxcontrib/argdoc/test/testdocroot
reStructuredText documentation stubs for executable scripts in the test suite, and a Sphinx configuration file (conf.py) that runs sphinxcontrib.argdoc
sphinxcontrib/argdoc/test/testbuild
Expected rst output from Sphinx from sphinxcontrib.argdoc

Submodules

sphinxcontrib.argdoc.test.test_argdoc module

Test suite for sphinxcontrib.argdoc.

Test implementation
To add a test case for a new argparse configuration
  1. Create an executable script using argparse following the general form of the other tests. Put it in the subpackage sphinxcontrib.argdoc.test.cases
  2. Create a matching rst document stub, and put it into sphinxcontrib/argdoc/test/testdocroot
  3. Add an entry for the rst document stub in sphinxcontrib/argdoc/test/testdocroot/master_toctree.rst
class sphinxcontrib.argdoc.test.test_argdoc.TestArgdoc[source]

Test case for functions defined in sphinxcontrib.argdoc.ext

Methods

check_equal(expected, found[, casename]) Helper method just to allow us to use test generators in other tests
check_list_equal(l1, l2, test_name)
check_not_match(pattern, inp, msg)
check_pattern(test_name, pat, inp, expected) Check patterns for matching, or non-matching
run_builder() Run sphinx builder only the first time it is needed
setUpClass()
tearDownClass() Clean up temp files after tests are complete
test_format_argparser_as_docstring()
test_get_col1_text()
test_get_col2_text()
test_make_rest_table_with_indent()
test_make_rest_table_with_title()
test_make_rest_table_without_title()
test_noargdoc_adds_attribute()
test_patterns()
test_post_process_automodule()
test_post_process_automodule_emits_event()
test_prefix_chars_does_not_match_wrong()
test_prefix_chars_does_not_mix()
test_prefix_chars_matches()
classmethod setUpClass()[source]
classmethod tearDownClass()[source]

Clean up temp files after tests are complete

classmethod run_builder()[source]

Run sphinx builder only the first time it is needed

Raises:

AssertionError

If builder exists with non-zero status

static check_pattern(test_name, pat, inp, expected)[source]

Check patterns for matching, or non-matching

Parameters:

test_name : str

Name of test set being executed

pat : re.compile

Pattern to test

inp : str

Input to test

expected : dict, tuple, or None

Expected result. If a dict, equivalence is tested with pat.match(inp).groupdict() is called to test equivalence. If a ‘tuple’ equivalence is tested with pat.match(inp).groups(), re.compile.groups() is called. If None, it is asserted that pat.match(inp) is None

test_patterns()[source]
static check_equal(expected, found, casename='')[source]

Helper method just to allow us to use test generators in other tests

test_prefix_chars_matches()[source]
static check_not_match(pattern, inp, msg)[source]
test_prefix_chars_does_not_match_wrong()[source]
test_prefix_chars_does_not_mix()[source]
test_get_col1_text()[source]
test_get_col2_text()[source]
test_make_rest_table_with_title()[source]
test_make_rest_table_without_title()[source]
test_make_rest_table_with_indent()[source]
test_noargdoc_adds_attribute()[source]
static check_list_equal(l1, l2, test_name)[source]
test_format_argparser_as_docstring()[source]
test_post_process_automodule()[source]
test_post_process_automodule_emits_event()[source]
class sphinxcontrib.argdoc.test.test_argdoc.Record[source]

Bases: object

Proxy object that allows addition of arbitrary properties

__init__()[source]
class sphinxcontrib.argdoc.test.test_argdoc.FakeApp(argdoc_main_func='main', argdoc_save_rst=True, outdir='/tmp/', argdoc_prefix_chars='-')[source]

Bases: object

Proxy for a Sphinx application object. Implements minimial methods required for us to test functions in sphinxcontrib.argdoc.ext that require a Sphinx application instance

Methods

debug(*args, **kwargs)
debug2(*args, **kwargs)
emit(*args, **kwargs) Simulate emit method.
warn(*args, **kwargs)
__init__(argdoc_main_func='main', argdoc_save_rst=True, outdir='/tmp/', argdoc_prefix_chars='-')[source]
warn(*args, **kwargs)[source]
debug(*args, **kwargs)[source]
debug2(*args, **kwargs)[source]
emit(*args, **kwargs)[source]

Simulate emit method. Save event name in self.emitted at each call

Subpackages

sphinxcontrib.argdoc.test.cases package

Modules in this package are executable scripts that serve as test cases for argdoc.test.test_argdoc. They cover a variety of argparse configurations.

Submodules
sphinxcontrib.argdoc.test.cases.c1_argument_group module

Argument groups with short, long, or no descriptions

ArgumentParser allows organization of arguments into argument groups, which can make things more intelligible for users. sphinxcontrib.argdoc styles argument groups as separate, paragraph-level sections, with their descriptions (if present) appearing below the title, followed by the arguments in each group, formatted as a table. Examples appear here below.


Command-line arguments
Positional arguments
Argument Description
mainarg1  
mainarg2 main positional argument #2
Optional arguments
Argument Description
-h, --help show this help message and exit
One group of arguments

Sometimes it is useful to group arguments that relate to each other in an argument group. This can make command-line help, documentation, and source code more intelligible to others

Argument Description
fooarg1 foo argument 1
fooarg2 foo argument 2
-f  F short foo argument
--fookwarg  FOOKWARG foo keyword argument
-v  VERBOSE, --verbose  VERBOSE foo verbosely
A second group of arguments

Description of second argument group

Argument Description
bararg bar argument
--choice  {option1,option2,option3} A keyword that requries a choice
A final group of arguments, with no description
Argument Description
bazarg baz argument
--numbers  M M M numerical argument
-z  ZOOM, --zoom  ZOOM zzzzzzzzzzzzzz

Script contents
sphinxcontrib.argdoc.test.cases.c1_argument_group.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]
sphinxcontrib.argdoc.test.cases.c2_only_subparsers module

Subcommands with no main program arguments

ArgumentParser supports use of subcommands, each of which might have their own arguments and argument groups. Here these are tested for a parser that has none of its own arguments, except --help.


Command-line arguments
Optional arguments
Argument Description
-h, --help show this help message and exit
Subcommands

choose one of the following:

Argument Description
foo Run the foo subprogram
bar Take output from foo subprogram and run it through the bar subprogram

foo subcommand

This is a long description of what a foo program might do. It spans multiple lines, so that we can test things reasonably.

Positional arguments
Argument Description
fooarg1 foo argument 1
fooarg2 foo argument 2
Optional arguments
Argument Description
-h, --help show this help message and exit
-f  F short foo argument
--fookwarg  FOOKWARG foo keyword argument
-v  VERBOSE, --verbose  VERBOSE foo verbosely

bar subcommand

This is the long description for the bar subprogram.

Positional arguments
Argument Description
bararg bar argument
Optional arguments
Argument Description
-h, --help show this help message and exit
--choice  {option1,option2,option3} A keyword that requries a choice

Script contents
sphinxcontrib.argdoc.test.cases.c2_only_subparsers.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]
sphinxcontrib.argdoc.test.cases.c3_main_plus_subparsers module

Subcommands with main program arguments

In this test case, we test a parser that has its own arguments as well as multiple subcommands, for which individual help sections should be generated.


Command-line arguments
Positional arguments
Argument Description
mainarg1  
mainarg2 main positional argument #2
Optional arguments
Argument Description
-h, --help show this help message and exit
Subcommands

choose one of the following:

Argument Description
foo Run the foo subprogram
bar Take output from foo subprogram and run it through the bar subprogram

foo subcommand

This is a long description of what a foo program might do. It spans multiple lines, so that we can test things reasonably.

Positional arguments
Argument Description
fooarg1 foo argument 1
fooarg2 foo argument 2
Optional arguments
Argument Description
-h, --help show this help message and exit
-f  F short foo argument
--fookwarg  FOOKWARG foo keyword argument
-v  VERBOSE, --verbose  VERBOSE foo verbosely

bar subcommand

This is the long description for the bar subprogram.

Positional arguments
Argument Description
bararg bar argument
Optional arguments
Argument Description
-h, --help show this help message and exit
--choice  {option1,option2,option3} A keyword that requries a choice
An argument group

A special goup of arguments in the bar subparser

Argument Description
--b1  B1  
--b2  B2 Argument 2 has help (bar argument 1 did not have help)
-k  N N Some other argument

Script contents
sphinxcontrib.argdoc.test.cases.c3_main_plus_subparsers.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]
sphinxcontrib.argdoc.test.cases.c4_with_long_subparsers module

Long-named subcommands, with main program arguments

In this test case, we test a parser that has its own arguments as well as multiple subcommands, one of which has an exceedingly long name. This is mostly to test column alignment.

We also added a bunch of paragraphs and rich formatting to show how reStructuredText markup survives post-processing by sphinxcontrib.argdoc.


Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean feugiat tempor diam sed condimentum. Mauris aliquam interdum libero, ut aliquet erat malesuada sed. Mauris nec venenatis sapien, a feugiat neque. Sed pulvinar erat sit amet posuere aliquet. Phasellus non quam tincidunt, semper velit vitae, eleifend ante. Nam finibus vulputate diam. Fusce sit amet leo aliquam magna gravida fringilla et eu justo. Pellentesque vulputate elit id dignissim vehicula. Sed tempor interdum lacus, in dapibus magna interdum eu. Fusce lacinia turpis vel risus porta, eget dapibus nisi eleifend. Maecenas dictum nec nisi sit amet dignissim. Duis vestibulum ipsum a vestibulum placerat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam consequat nulla quis quam interdum, eu auctor ante molestie.

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut egestas nec leo a luctus. Suspendisse libero magna, ultricies vel porttitor varius, vulputate nec orci. Ut et vehicula neque. Quisque ut libero eget sem pretium mollis elementum vitae quam. Etiam varius rutrum iaculis. Mauris consectetur cursus dolor nec tincidunt. Morbi aliquam elit ipsum, at aliquam purus ultricies sed. Donec tortor ante, consectetur et faucibus non, dignissim vitae eros. Duis pharetra convallis efficitur. Curabitur congue in tortor luctus molestie. Donec turpis felis, sollicitudin volutpat tristique quis, mattis at arcu. Praesent interdum luctus sodales. Sed imperdiet augue vulputate hendrerit tincidunt. Curabitur pharetra, odio in laoreet pretium, metus turpis posuere dui, quis aliquet leo nisl sollicitudin ligula.

Here is a table, to show that we can have rich formatting:

Column 1 Column 2
Some item Some other item.
Table row 2. Table row 2 column 2.
Another row. Row with a link to Python
See also
A definition list
The purpose of this See also section is just to show that we can use a number of reStructuredText structures, and still have the argument descriptions appended below.
Here is another item
To show that our test works

Command-line arguments
Positional arguments
Argument Description
mainarg1  
mainarg2 main positional argument #2, which we wrote helptext for (there was no help for mainarg1)
Optional arguments
Argument Description
-h, --help show this help message and exit
Subcommands

choose one of the following:

Argument Description
foo Run the foo subprogram
barbarbarbarbaraaeadslfjasdlkfjljalksjflsjdfladjfklasdjkfladsjglkjdasl Take output from foo subprogram and run it through the bar subprogram

foo subcommand

This is a long description of what a foo program might do. It spans multiple lines, so that we can test things reasonably.

Positional arguments
Argument Description
fooarg1 foo argument 1
fooarg2 foo argument 2
Optional arguments
Argument Description
-h, --help show this help message and exit
-f  F short foo argument
--fookwarg  FOOKWARG foo keyword argument
-v  VERBOSE, --verbose  VERBOSE foo verbosely

barbarbarbarbaraaeadslfjasdlkfjljalksjflsjdfladjfklasdjkfladsjglkjdasl subcommand

This is the long description for the bar subprogram.

Positional arguments
Argument Description
bararg bar argument
Optional arguments
Argument Description
-h, --help show this help message and exit
--choice  {option1,option2,option3} A keyword that requries a choice
An argument group

A special goup of arguments in the bar subparser

Argument Description
--b1  B1  
--b2  B2 Argument 2 has help (bar argument 1 did not)
-k  N N Some other argument

Script contents
sphinxcontrib.argdoc.test.cases.c4_with_long_subparsers.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]
sphinxcontrib.argdoc.test.cases.c5_with_epilog module

Subcommands, each having its own epilog

An epilog should appear at the bottom of each command-group section


Command-line arguments
Positional arguments
Argument Description
mainarg1  
mainarg2 main positional argument #2, which has a description (mainarg1 did not)
Optional arguments
Argument Description
-h, --help show this help message and exit
Subcommands

choose one of the following:

Argument Description
foo Run the foo subprogram
bar Take output from foo subprogram and run it through the bar subprogram

This is a multi-line epilog which should appear at the bottom of the module docstring and also follow all of the options, arguments, et cetera.


foo subcommand

This is a long description of what a foo program might do. It spans multiple lines, so that we can test things reasonably.

Positional arguments
Argument Description
fooarg1 foo argument 1
fooarg2 foo argument 2
Optional arguments
Argument Description
-h, --help show this help message and exit
-f  F short foo argument
--fookwarg  FOOKWARG foo keyword argument
-v  VERBOSE, --verbose  VERBOSE foo verbosely

This is the epilog for the foo subprogram. It should appear at the end of the foo subcommand section.


bar subcommand

This is the long description for the bar subcommand.

Positional arguments
Argument Description
bararg bar argument
Optional arguments
Argument Description
-h, --help show this help message and exit
--choice  {option1,option2,option3} A keyword that requries a choice
An argument group

A special goup of arguments in the bar subparser

Argument Description
--b1  B1  
--b2  B2 Argument 2 has help
-k  N N Some other argument

This the epilog for the bar subcommand. It is short.


Script contents
sphinxcontrib.argdoc.test.cases.c5_with_epilog.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]
sphinxcontrib.argdoc.test.cases.c6_multiprefix module

Multiple prefix characters

ArgumentParser takes a prefix_chars option which allows the use of keyword arguments that begin with characters other than ‘-‘. Here we test a ArgumentParser that uses both ‘-‘ and ‘+’.


Command-line arguments
Positional arguments
Argument Description
shortpos1  
shortpos2 one-line help text
shortpos3 this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument1  
reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument2 one-line help text
reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument3 this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
Optional arguments
Argument Description
-h, --help show this help message and exit
-a  X  
--bar  X one-line help text
--c  X X, --arg3  X X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
+x  X  
++another  ANOTHER Another argument
+y  ARG4 [ARG4 ...], ++arg4  ARG4 [ARG4 ...] An argument beginning with ‘+’

Script contents
sphinxcontrib.argdoc.test.cases.c6_multiprefix.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]

Command-line program for simple_parser

sphinxcontrib.argdoc.test.cases.c7_nosphinxcontrib.argdoc module

Use of ‘noargdoc’ function decorator

The noargdoc() function decorator tells sphinxcontrib.argdoc to ignore a command-line script, leaving its :automodule: output unchanged.


Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean feugiat tempor diam sed condimentum. Mauris aliquam interdum libero, ut aliquet erat malesuada sed. Mauris nec venenatis sapien, a feugiat neque. Sed pulvinar erat sit amet posuere aliquet. Phasellus non quam tincidunt, semper velit vitae, eleifend ante. Nam finibus vulputate diam. Fusce sit amet leo aliquam magna gravida fringilla et eu justo. Pellentesque vulputate elit id dignissim vehicula. Sed tempor interdum lacus, in dapibus magna interdum eu. Fusce lacinia turpis vel risus porta, eget dapibus nisi eleifend. Maecenas dictum nec nisi sit amet dignissim. Duis vestibulum ipsum a vestibulum placerat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam consequat nulla quis quam interdum, eu auctor ante molestie.

Here is a table, to show that we can have rich formatting:

Column 1 Column 2
Some item Some other item.
Table row 2. Table row 2 column 2.
Another row. Row with a link to Python
See also
A definition list
The purpose of this See also section is just to show that we can use a number of reStructuredText structures, and still have the argument descriptions appended below.
Here is another item
To show that our test works
sphinxcontrib.argdoc.test.cases.c7_noargdoc.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]

Command-line program for simple_parser

sphinxcontrib.argdoc.test.cases.c8_exhaustive module

Exhaustively test all argument types

The following argument attributes are tested in all combinations to ensure they are all properly parsed and rendered:

  • arguments with short or long names
  • positional arguments
  • keyword arguments starting with ‘-‘, ‘–’, or both
  • arguments taking 0, 1, 2, (0 or more), (1 or more), or (0 or 1) arguments
  • arguments taking choices of 1 or more items
  • arguments with no help text
  • arguments with short help text, which tends to be displayed on one line by argparse
  • arguments with long help text, which tends to appear on multiple lines
  • arguments including or excluding unicode characters in their names

Here is a table, to show that we can have rich formatting in the module docstring, without sphinxcontrib.argdoc inadvertently introducing problems:

Column 1 Column 2
Some item Some other item.
Table row 2. Table row 2 column 2.
Another row. Row with a link to Python
See also
A definition list
The purpose of this See also section is just to show that we can use a number of reStructuredText structures in the module docstring, and still have the argument descriptions appended below.
Here is another item
To show that our test works

Command-line arguments
Positional arguments
Argument Description
shortpos1  
shortpos2 one-line help text
shortpos3 this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument1  
reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument2 one-line help text
reallyreallyreallyreallyreallyreallyreallyreallylongpositionalargument3 this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
Optional arguments
Argument Description
-h, --help show this help message and exit
-a  X  
-b  X one-line help text
-c  X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--double1  X  
--double2  X one-line help text
--double3  X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-d  X, --combo1  X  
-e  X, --combo2  X one-line help text
-f  X, --combo3  X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--reallyreallyreallyreallyreallyreallylong_double1  X  
--reallyreallyreallyreallyreallyreallylong_double2  X one-line help text
--reallyreallyreallyreallyreallyreallylong_double3  X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-g  X, --reallyreallyreallyreallyreallyreallylong_combo1  X  
-i  X, --reallyreallyreallyreallyreallyreallylong_combo2  X one-line help text
-j  X, --reallyreallyreallyreallyreallyreallylong_combo3  X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-k  X X  
-l  X X one-line help text
-m  X X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--double4  X X  
--double5  X X one-line help text
--double6  X X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-n  X X, --combo4  X X  
-o  X X, --combo5  X X one-line help text
-p  X X, --combo6  X X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--reallyreallyreallyreallyreallyreallylong_double4  X X  
--reallyreallyreallyreallyreallyreallylong_double5  X X one-line help text
--reallyreallyreallyreallyreallyreallylong_double6  X X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-q  X X, --reallyreallyreallyreallyreallyreallylong_combo4  X X  
-r  X X, --reallyreallyreallyreallyreallyreallylong_combo5  X X one-line help text
-s  X X, --reallyreallyreallyreallyreallyreallylong_combo6  X X this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-t  X [X ...]  
-u  X [X ...] one-line help text
-v  X [X ...] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--double7  X [X ...]  
--double8  X [X ...] one-line help text
--double9  X [X ...] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-w  X [X ...], --combo7  X [X ...]  
-x  X [X ...], --combo8  X [X ...] one-line help text
-y  X [X ...], --combo9  X [X ...] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--reallyreallyreallyreallyreallyreallylong_double7  X [X ...]  
--reallyreallyreallyreallyreallyreallylong_double8  X [X ...] one-line help text
--reallyreallyreallyreallyreallyreallylong_double9  X [X ...] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-z  X [X ...], --reallyreallyreallyreallyreallyreallylong_combo7  X [X ...]  
-A  X [X ...], --reallyreallyreallyreallyreallyreallylong_combo8  X [X ...] one-line help text
-B  X [X ...], --reallyreallyreallyreallyreallyreallylong_combo9  X [X ...] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-C  [X]  
-D  [X] one-line help text
-E  [X] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--double10  [X]  
--double11  [X] one-line help text
--double12  [X] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-F  [X], --combo10  [X]  
-G  [X], --combo11  [X] one-line help text
-H  [X], --combo12  [X] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--reallyreallyreallyreallyreallyreallylong_double10  [X]  
--reallyreallyreallyreallyreallyreallylong_double11  [X] one-line help text
--reallyreallyreallyreallyreallyreallylong_double12  [X] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-I  [X], --reallyreallyreallyreallyreallyreallylong_combo10  [X]  
-J  [X], --reallyreallyreallyreallyreallyreallylong_combo11  [X] one-line help text
-K  [X], --reallyreallyreallyreallyreallyreallylong_combo12  [X] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-L  [X [X ...]]  
-M  [X [X ...]] one-line help text
-N  [X [X ...]] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--double13  [X [X ...]]  
--double14  [X [X ...]] one-line help text
--double15  [X [X ...]] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-O  [X [X ...]], --combo13  [X [X ...]]  
-P  [X [X ...]], --combo14  [X [X ...]] one-line help text
-Q  [X [X ...]], --combo15  [X [X ...]] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--reallyreallyreallyreallyreallyreallylong_double13  [X [X ...]]  
--reallyreallyreallyreallyreallyreallylong_double14  [X [X ...]] one-line help text
--reallyreallyreallyreallyreallyreallylong_double15  [X [X ...]] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-R  [X [X ...]], --reallyreallyreallyreallyreallyreallylong_combo13  [X [X ...]]  
-S  [X [X ...]], --reallyreallyreallyreallyreallyreallylong_combo14  [X [X ...]] one-line help text
-T  [X [X ...]], --reallyreallyreallyreallyreallyreallylong_combo15  [X [X ...]] this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-U  {one_choice}  
-V  {one_choice} one-line help text
-W  {one_choice} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--double16  {one_choice}  
--double17  {one_choice} one-line help text
--double18  {one_choice} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-X  {one_choice}, --combo16  {one_choice}  
-Y  {one_choice}, --combo17  {one_choice} one-line help text
-Z  {one_choice}, --combo18  {one_choice} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--reallyreallyreallyreallyreallyreallylong_double16  {one_choice}  
--reallyreallyreallyreallyreallyreallylong_double17  {one_choice} one-line help text
--reallyreallyreallyreallyreallyreallylong_double18  {one_choice} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-1  {one_choice}, --reallyreallyreallyreallyreallyreallylong_combo16  {one_choice}  
-2  {one_choice}, --reallyreallyreallyreallyreallyreallylong_combo17  {one_choice} one-line help text
-3  {one_choice}, --reallyreallyreallyreallyreallyreallylong_combo18  {one_choice} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-4  {one,two,three,four}  
-5  {one,two,three,four} one-line help text
-6  {one,two,three,four} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--double19  {one,two,three,four}  
--double20  {one,two,three,four} one-line help text
--double21  {one,two,three,four} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
-7  {one,two,three,four}, --combo19  {one,two,three,four}  
-8  {one,two,three,four}, --combo20  {one,two,three,four} one-line help text
-9  {one,two,three,four}, --combo21  {one,two,three,four} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
--reallyreallyreallyreallyreallyreallylong_double19  {one,two,three,four}  
--reallyreallyreallyreallyreallyreallylong_double20  {one,two,three,four} one-line help text
--reallyreallyreallyreallyreallyreallylong_double21  {one,two,three,four} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)
  {one,two,three,four}, --reallyreallyreallyreallyreallyreallylong_combo19  {one,two,three,four}  
  {one,two,three,four}, --reallyreallyreallyreallyreallyreallylong_combo20  {one,two,three,four} one-line help text
  {one,two,three,four}, --reallyreallyreallyreallyreallyreallylong_combo21  {one,two,three,four} this is very, very long help text which should span multiple lines and thus require special parsing. We’ll also add special chars (default: 513251324)

Script contents
sphinxcontrib.argdoc.test.cases.c8_exhaustive.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]

Command-line program for simple_parser

sphinxcontrib.argdoc.test.cases.c9_subsubparsers

Subcommands of subcommands

In this test case, we test a parser that has its own arguments as well as multiple subcommands, which have their own subcommands that must be included as subsections within them. Here, the foo subcommand has subcommands, but the bar subcommand does not.


Command-line arguments
Positional arguments
Argument Description
mainarg1  
mainarg2 main positional argument #2
Optional arguments
Argument Description
-h, --help show this help message and exit
Subcommands

choose one of the following:

Argument Description
foo Run the foo subcommand
bar Take output from foo subprogram and run it through the bar subprogram

foo subcommand

This is a long description of what a foo program might do. It spans multiple lines, so that we can test things reasonably.

Positional arguments
Argument Description
fooarg1 foo argument 1
fooarg2 foo argument 2
Optional arguments
Argument Description
-h, --help show this help message and exit
-f  F short foo argument
--fookwarg  FOOKWARG foo keyword argument
-v  VERBOSE, --verbose  VERBOSE foo verbosely
Subcommands of the foo subcommand

this is indeed unusual

Argument Description
subfoo1 Run the subfoo1 subcommand of the foo subcommand
subfoo2 Run the subfoo2 subcommand of the foo subcommand
subfoo3 Run the subfoo3 subcommand of the foo subcommand

foo-subfoo1 subcommand

Subcommands of subcommands are an unusual use case, but it seemed worth testing

Optional arguments
Argument Description
-h, --help show this help message and exit

foo-subfoo2 subcommand

This is a multi-line subcommand description intended to test whether or not sphinxcontrib.argdoc can correctly format these. If this text is correctly formatted, it will end at the end of this sentence.

Optional arguments
Argument Description
-h, --help show this help message and exit

foo-subfoo3 subcommand
Optional arguments
Argument Description
-h, --help show this help message and exit

bar subcommand

This is the long description for the bar subprogram.

Positional arguments
Argument Description
bararg bar argument
Optional arguments
Argument Description
-h, --help show this help message and exit
--choice  {option1,option2,option3} A keyword that requries a choice
An argument group

A special goup of arguments in the bar subparser

Argument Description
--b1  B1  
--b2  B2 Argument 2 has help (bar argument 1 did not have help)
-k  N N Some other argument

Script contents
sphinxcontrib.argdoc.test.cases.c9_subsubparsers.main(argv=['-T', '-b', 'readthedocssinglehtmllocalmedia', '-D', 'language=en', '.', '_build/localmedia'])[source]