Sphinx Argparse Extension

0.5.2 · active · verified Thu Apr 09

sphinx-argparse is a Sphinx extension that automatically documents `argparse` commands and options by parsing Python scripts or functions. It helps generate command-line interface documentation directly from your `argparse` definitions. The current version is 0.5.2, and it maintains a moderate release cadence, with several updates per year.

Warnings

Install

Imports

Quickstart

To use `sphinx-argparse`, first add `'sphinx_argparse'` to your `extensions` list in `conf.py`. Then, create a Python script with an `argparse.ArgumentParser` definition. Finally, use the `.. argparse::` directive in your reStructuredText or MyST documentation files, pointing to the script or a function that returns the parser. You can specify the `prog` name and other options.

# conf.py
import os
import sys
sys.path.insert(0, os.path.abspath('.'))

project = 'My Project'
copyright = '2023, Your Name'
extensions = [
    'sphinx_argparse'
]

# my_script.py (example script to document)
import argparse

def main():
    parser = argparse.ArgumentParser(description='A sample command line tool.')
    parser.add_argument('--foo', help='The foo argument.', default='bar')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
    subparsers = parser.add_subparsers(dest='command', help='sub-command help')
    
    parser_a = subparsers.add_parser('subcommand-a', help='subcommand a help')
    parser_a.add_argument('--baz', help='The baz argument for subcommand a.')

    args = parser.parse_args()
    print(f'Args: {args}')

if __name__ == '__main__':
    main()

# my_documentation_page.rst
# .. argparse:: my_script.py
#    :func: main.parser
#    :prog: my-cli
#
# (Note: For this example, you would place `my_script.py` in the same directory as `conf.py` or adjust `sys.path` accordingly.)

view raw JSON →