@@ -788,6 +788,59 @@ but not both at the same time:
788
788
-q, --quiet
789
789
790
790
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
+
791
844
Conclusion
792
845
==========
793
846
0 commit comments