Debian Codegraph @

docs/howto/cmdline-tool.rst

raw
1 .. include:: ../header.rst
2
3 ===============================================
4 Inside A Docutils Command-Line Front-End Tool
5 ===============================================
6
7 :Author: David Goodger
8 :Contact: [email protected]
9 :Date: $Date: 2024-08-15 10:43:38 +0200 (Do, 15. Aug 2024) $
10 :Revision: $Revision: 9906 $
11 :Copyright: This document has been placed in the public domain.
12
13 .. note:: This document describes the traditional approach with
14 hand-crafted front-end scripts.
15 Since version 0.21, the package installer installs
16 front-end scripts generated from "console_scripts"
17 `entry point`_ definitions.
18
19 `The Docutils Publisher`_ class was set up to make building
20 command-line tools easy. All that's required is to choose components
21 and supply settings for variations. Let's take a look at a typical
22 command-line front-end tool, ``tools/rst2html.py``, from top to
23 bottom.
24
25 On Unixish systems, it's best to make the file executable (``chmod +x
26 file``), and supply an interpreter on the first line, the "shebang" or
27 "hash-bang" line::
28
29 #!/usr/bin/env python
30
31 Windows systems can be set up to associate the Python interpreter with
32 the ``.py`` extension.
33
34 Next are some comments providing metadata::
35
36 # $Id: cmdline-tool.rst 9906 2024-08-15 08:43:38Z grubert $
37 # Author: David Goodger <[email protected]>
38 # Copyright: This module has been placed in the public domain.
39
40 The module docstring describes the purpose of the tool::
41
42 """
43 A minimal front end to the Docutils Publisher, producing HTML.
44 """
45
46 This next block attempts to invoke locale support for
47 internationalization services. It's not
48 supported on all platforms though, so it's forgiving::
49
50 try:
51 import locale
52 locale.setlocale(locale.LC_ALL, '')
53 except:
54 pass
55
56 The real work will be done by the code that's imported here::
57
58 from docutils.core import publish_cmdline, default_description
59
60 We construct a description of the tool, for command-line help::
61
62 description = ('Generates (X)HTML documents from standalone '
63 'reStructuredText sources. ' + default_description)
64
65 Now we call the Publisher convenience function, which takes over.
66 Most of its defaults are used ("standalone" Reader,
67 "reStructuredText" Parser, etc.). The HTML Writer is chosen by name,
68 and a description for command-line help is passed in::
69
70 publish_cmdline(writer='html', description=description)
71
72 That's it! `The Docutils Publisher`_ takes care of the rest.
73
74
75 .. _entry point:
76 https://packaging.python.org/en/latest/specifications/entry-points/
77 .. _The Docutils Publisher: ./publisher.html