Skip to content

Commit ff2c6cd

Browse files
committed
Add argparse i18n howto
1 parent 8a3702f commit ff2c6cd

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

Doc/howto/argparse.rst

Lines changed: 53 additions & 0 deletions
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+
Internationalization support
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`. (If you are not familiar with Internationalization and
798+
Localization, you can check out :ref:`i18n-howto`).
799+
800+
For instance, in this :mod:`argparse` output:
801+
802+
.. code-block:: shell-session
803+
804+
$ python prog.py --help
805+
usage: prog.py [-h] [-v | -q] x y
806+
807+
calculate X to the power of Y
808+
809+
positional arguments:
810+
x the base
811+
y the exponent
812+
813+
options:
814+
-h, --help show this help message and exit
815+
-v, --verbose
816+
-q, --quiet
817+
818+
The strings ``usage:``, ``positional arguments:``, ``options:`` and
819+
``show this help message and exit`` are all translatable.
820+
821+
In order to translate these strings, you will probably want to extract them
822+
into a ``.po`` file. For example, using `Babel <https://babel.pocoo.org/>`__,
823+
you can run:
824+
825+
.. code-block:: shell-session
826+
827+
$ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py
828+
829+
This command will extract all translatable strings from the :mod:`argparse`
830+
module and output them into a file named ``messages.po``. This command assumes
831+
that your Python installation is in ``/usr/lib``.
832+
833+
You can find out the location of the :mod:`argparse` module on your system
834+
using this simple script::
835+
836+
import argparse
837+
print(argparse.__file__)
838+
839+
Once the messages in the ``.po`` file are translated and the translations are
840+
installed using :mod:`gettext`, :mod:`argparse` will be able to display the
841+
translated messages.
842+
843+
791844
Conclusion
792845
==========
793846

Doc/library/gettext.rst

Lines changed: 1 addition & 0 deletions
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
--------------------------------------------

0 commit comments

Comments
 (0)