@@ -759,6 +759,59 @@ but not both at the same time:
759
759
-q, --quiet
760
760
761
761
762
+ How to translate the argparse output
763
+ ====================================
764
+
765
+ The output of the :mod: `argparse ` module such as its help text and error
766
+ messages are all made translatable using the :mod: `gettext ` module. This
767
+ allows applications to easily localize messages produced by
768
+ :mod: `argparse `. See also :ref: `i18n-howto `.
769
+
770
+ For instance, in this :mod: `argparse ` output:
771
+
772
+ .. code-block :: shell-session
773
+
774
+ $ python prog.py --help
775
+ usage: prog.py [-h] [-v | -q] x y
776
+
777
+ calculate X to the power of Y
778
+
779
+ positional arguments:
780
+ x the base
781
+ y the exponent
782
+
783
+ options:
784
+ -h, --help show this help message and exit
785
+ -v, --verbose
786
+ -q, --quiet
787
+
788
+ The strings ``usage: ``, ``positional arguments: ``, ``options: `` and
789
+ ``show this help message and exit `` are all translatable.
790
+
791
+ In order to translate these strings, they must first be extracted
792
+ into a ``.po `` file. For example, using `Babel <https://babel.pocoo.org/ >`__,
793
+ run this command:
794
+
795
+ .. code-block :: shell-session
796
+
797
+ $ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py
798
+
799
+ This command will extract all translatable strings from the :mod: `argparse `
800
+ module and output them into a file named ``messages.po ``. This command assumes
801
+ that your Python installation is in ``/usr/lib ``.
802
+
803
+ You can find out the location of the :mod: `argparse ` module on your system
804
+ using this script::
805
+
806
+ import argparse
807
+ print(argparse.__file__)
808
+
809
+ Once the messages in the ``.po `` file are translated and the translations are
810
+ installed using :mod: `gettext `, :mod: `argparse ` will be able to display the
811
+ translated messages.
812
+
813
+ To translate your own strings in the :mod: `argparse ` output, use :mod: `gettext `.
814
+
762
815
Conclusion
763
816
==========
764
817
0 commit comments