Skip to content

Commit dcd7acb

Browse files
authored
gh-54738: Add argparse i18n howto (#104562)
1 parent 680f3e1 commit dcd7acb

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

Doc/howto/argparse.rst

+53
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,59 @@ but not both at the same time:
788788
-q, --quiet
789789
790790
791+
How to translate the argparse output
792+
====================================
793+
794+
The output of the :mod:`argparse` module such as its help text and error
795+
messages are all made translatable using the :mod:`gettext` module. This
796+
allows applications to easily localize messages produced by
797+
:mod:`argparse`. See also :ref:`i18n-howto`.
798+
799+
For instance, in this :mod:`argparse` output:
800+
801+
.. code-block:: shell-session
802+
803+
$ python prog.py --help
804+
usage: prog.py [-h] [-v | -q] x y
805+
806+
calculate X to the power of Y
807+
808+
positional arguments:
809+
x the base
810+
y the exponent
811+
812+
options:
813+
-h, --help show this help message and exit
814+
-v, --verbose
815+
-q, --quiet
816+
817+
The strings ``usage:``, ``positional arguments:``, ``options:`` and
818+
``show this help message and exit`` are all translatable.
819+
820+
In order to translate these strings, they must first be extracted
821+
into a ``.po`` file. For example, using `Babel <https://babel.pocoo.org/>`__,
822+
run this command:
823+
824+
.. code-block:: shell-session
825+
826+
$ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py
827+
828+
This command will extract all translatable strings from the :mod:`argparse`
829+
module and output them into a file named ``messages.po``. This command assumes
830+
that your Python installation is in ``/usr/lib``.
831+
832+
You can find out the location of the :mod:`argparse` module on your system
833+
using this script::
834+
835+
import argparse
836+
print(argparse.__file__)
837+
838+
Once the messages in the ``.po`` file are translated and the translations are
839+
installed using :mod:`gettext`, :mod:`argparse` will be able to display the
840+
translated messages.
841+
842+
To translate your own strings in the :mod:`argparse` output, use :mod:`gettext`.
843+
791844
Conclusion
792845
==========
793846

Doc/library/gettext.rst

+1
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,7 @@ One difference between this module and Henstridge's: his catalog objects
411411
supported access through a mapping API, but this appears to be unused and so is
412412
not currently supported.
413413

414+
.. _i18n-howto:
414415

415416
Internationalizing your programs and modules
416417
--------------------------------------------
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add documentation on how to localize the :mod:`argparse` module.

0 commit comments

Comments
 (0)