Debian Codegraph @

Doc/howto/argparse.rst

raw
1 .. _argparse-tutorial:
2
3 *****************
4 Argparse Tutorial
5 *****************
6
7 :author: Tshepang Mbambo
8
9 .. currentmodule:: argparse
10
11 This tutorial is intended to be a gentle introduction to :mod:`argparse`, the
12 recommended command-line parsing module in the Python standard library.
13
14 .. note::
15
16 The standard library includes two other libraries directly related
17 to command-line parameter processing: the lower level :mod:`optparse`
18 module (which may require more code to configure for a given application,
19 but also allows an application to request behaviors that ``argparse``
20 doesn't support), and the very low level :mod:`getopt` (which specifically
21 serves as an equivalent to the :c:func:`!getopt` family of functions
22 available to C programmers).
23 While neither of those modules is covered directly in this guide, many of
24 the core concepts in ``argparse`` first originated in ``optparse``, so
25 some aspects of this tutorial will also be relevant to ``optparse`` users.
26
27
28 Concepts
29 ========
30
31 Let's show the sort of functionality that we are going to explore in this
32 introductory tutorial by making use of the :command:`ls` command:
33
34 .. code-block:: shell-session
35
36 $ ls
37 cpython devguide prog.py pypy rm-unused-function.patch
38 $ ls pypy
39 ctypes_configure demo dotviewer include lib_pypy lib-python ...
40 $ ls -l
41 total 20
42 drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
43 drwxr-xr-x 4 wena wena 4096 Feb 8 12:04 devguide
44 -rwxr-xr-x 1 wena wena 535 Feb 19 00:05 prog.py
45 drwxr-xr-x 14 wena wena 4096 Feb 7 00:59 pypy
46 -rw-r--r-- 1 wena wena 741 Feb 18 01:01 rm-unused-function.patch
47 $ ls --help
48 Usage: ls [OPTION]... [FILE]...
49 List information about the FILEs (the current directory by default).
50 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
51 ...
52
53 A few concepts we can learn from the four commands:
54
55 * The :command:`ls` command is useful when run without any options at all. It defaults
56 to displaying the contents of the current directory.
57
58 * If we want beyond what it provides by default, we tell it a bit more. In
59 this case, we want it to display a different directory, ``pypy``.
60 What we did is specify what is known as a positional argument. It's named so
61 because the program should know what to do with the value, solely based on
62 where it appears on the command line. This concept is more relevant
63 to a command like :command:`cp`, whose most basic usage is ``cp SRC DEST``.
64 The first position is *what you want copied,* and the second
65 position is *where you want it copied to*.
66
67 * Now, say we want to change behaviour of the program. In our example,
68 we display more info for each file instead of just showing the file names.
69 The ``-l`` in that case is known as an optional argument.
70
71 * That's a snippet of the help text. It's very useful in that you can
72 come across a program you have never used before, and can figure out
73 how it works simply by reading its help text.
74
75
76 The basics
77 ==========
78
79 Let us start with a very simple example which does (almost) nothing::
80
81 import argparse
82 parser = argparse.ArgumentParser()
83 parser.parse_args()
84
85 Following is a result of running the code:
86
87 .. code-block:: shell-session
88
89 $ python prog.py
90 $ python prog.py --help
91 usage: prog.py [-h]
92
93 options:
94 -h, --help show this help message and exit
95 $ python prog.py --verbose
96 usage: prog.py [-h]
97 prog.py: error: unrecognized arguments: --verbose
98 $ python prog.py foo
99 usage: prog.py [-h]
100 prog.py: error: unrecognized arguments: foo
101
102 Here is what is happening:
103
104 * Running the script without any options results in nothing displayed to
105 stdout. Not so useful.
106
107 * The second one starts to display the usefulness of the :mod:`argparse`
108 module. We have done almost nothing, but already we get a nice help message.
109
110 * The ``--help`` option, which can also be shortened to ``-h``, is the only
111 option we get for free (i.e. no need to specify it). Specifying anything
112 else results in an error. But even then, we do get a useful usage message,
113 also for free.
114
115
116 Introducing Positional arguments
117 ================================
118
119 An example::
120
121 import argparse
122 parser = argparse.ArgumentParser()
123 parser.add_argument("echo")
124 args = parser.parse_args()
125 print(args.echo)
126
127 And running the code:
128
129 .. code-block:: shell-session
130
131 $ python prog.py
132 usage: prog.py [-h] echo
133 prog.py: error: the following arguments are required: echo
134 $ python prog.py --help
135 usage: prog.py [-h] echo
136
137 positional arguments:
138 echo
139
140 options:
141 -h, --help show this help message and exit
142 $ python prog.py foo
143 foo
144
145 Here is what's happening:
146
147 * We've added the :meth:`~ArgumentParser.add_argument` method, which is what we use to specify
148 which command-line options the program is willing to accept. In this case,
149 I've named it ``echo`` so that it's in line with its function.
150
151 * Calling our program now requires us to specify an option.
152
153 * The :meth:`~ArgumentParser.parse_args` method actually returns some data from the
154 options specified, in this case, ``echo``.
155
156 * The variable is some form of 'magic' that :mod:`argparse` performs for free
157 (i.e. no need to specify which variable that value is stored in).
158 You will also notice that its name matches the string argument given
159 to the method, ``echo``.
160
161 Note however that, although the help display looks nice and all, it currently
162 is not as helpful as it can be. For example we see that we got ``echo`` as a
163 positional argument, but we don't know what it does, other than by guessing or
164 by reading the source code. So, let's make it a bit more useful::
165
166 import argparse
167 parser = argparse.ArgumentParser()
168 parser.add_argument("echo", help="echo the string you use here")
169 args = parser.parse_args()
170 print(args.echo)
171
172 And we get:
173
174 .. code-block:: shell-session
175
176 $ python prog.py -h
177 usage: prog.py [-h] echo
178
179 positional arguments:
180 echo echo the string you use here
181
182 options:
183 -h, --help show this help message and exit
184
185 Now, how about doing something even more useful::
186
187 import argparse
188 parser = argparse.ArgumentParser()
189 parser.add_argument("square", help="display a square of a given number")
190 args = parser.parse_args()
191 print(args.square**2)
192
193 Following is a result of running the code:
194
195 .. code-block:: shell-session
196
197 $ python prog.py 4
198 Traceback (most recent call last):
199 File "prog.py", line 5, in <module>
200 print(args.square**2)
201 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
202
203 That didn't go so well. That's because :mod:`argparse` treats the options we
204 give it as strings, unless we tell it otherwise. So, let's tell
205 :mod:`argparse` to treat that input as an integer::
206
207 import argparse
208 parser = argparse.ArgumentParser()
209 parser.add_argument("square", help="display a square of a given number",
210 type=int)
211 args = parser.parse_args()
212 print(args.square**2)
213
214 Following is a result of running the code:
215
216 .. code-block:: shell-session
217
218 $ python prog.py 4
219 16
220 $ python prog.py four
221 usage: prog.py [-h] square
222 prog.py: error: argument square: invalid int value: 'four'
223
224 That went well. The program now even helpfully quits on bad illegal input
225 before proceeding.
226
227
228 Introducing Optional arguments
229 ==============================
230
231 So far we have been playing with positional arguments. Let us
232 have a look on how to add optional ones::
233
234 import argparse
235 parser = argparse.ArgumentParser()
236 parser.add_argument("--verbosity", help="increase output verbosity")
237 args = parser.parse_args()
238 if args.verbosity:
239 print("verbosity turned on")
240
241 And the output:
242
243 .. code-block:: shell-session
244
245 $ python prog.py --verbosity 1
246 verbosity turned on
247 $ python prog.py
248 $ python prog.py --help
249 usage: prog.py [-h] [--verbosity VERBOSITY]
250
251 options:
252 -h, --help show this help message and exit
253 --verbosity VERBOSITY
254 increase output verbosity
255 $ python prog.py --verbosity
256 usage: prog.py [-h] [--verbosity VERBOSITY]
257 prog.py: error: argument --verbosity: expected one argument
258
259 Here is what is happening:
260
261 * The program is written so as to display something when ``--verbosity`` is
262 specified and display nothing when not.
263
264 * To show that the option is actually optional, there is no error when running
265 the program without it. Note that by default, if an optional argument isn't
266 used, the relevant variable, in this case ``args.verbosity``, is
267 given ``None`` as a value, which is the reason it fails the truth
268 test of the :keyword:`if` statement.
269
270 * The help message is a bit different.
271
272 * When using the ``--verbosity`` option, one must also specify some value,
273 any value.
274
275 The above example accepts arbitrary integer values for ``--verbosity``, but for
276 our simple program, only two values are actually useful, ``True`` or ``False``.
277 Let's modify the code accordingly::
278
279 import argparse
280 parser = argparse.ArgumentParser()
281 parser.add_argument("--verbose", help="increase output verbosity",
282 action="store_true")
283 args = parser.parse_args()
284 if args.verbose:
285 print("verbosity turned on")
286
287 And the output:
288
289 .. code-block:: shell-session
290
291 $ python prog.py --verbose
292 verbosity turned on
293 $ python prog.py --verbose 1
294 usage: prog.py [-h] [--verbose]
295 prog.py: error: unrecognized arguments: 1
296 $ python prog.py --help
297 usage: prog.py [-h] [--verbose]
298
299 options:
300 -h, --help show this help message and exit
301 --verbose increase output verbosity
302
303 Here is what is happening:
304
305 * The option is now more of a flag than something that requires a value.
306 We even changed the name of the option to match that idea.
307 Note that we now specify a new keyword, ``action``, and give it the value
308 ``"store_true"``. This means that, if the option is specified,
309 assign the value ``True`` to ``args.verbose``.
310 Not specifying it implies ``False``.
311
312 * It complains when you specify a value, in true spirit of what flags
313 actually are.
314
315 * Notice the different help text.
316
317
318 Short options
319 -------------
320
321 If you are familiar with command line usage,
322 you will notice that I haven't yet touched on the topic of short
323 versions of the options. It's quite simple::
324
325 import argparse
326 parser = argparse.ArgumentParser()
327 parser.add_argument("-v", "--verbose", help="increase output verbosity",
328 action="store_true")
329 args = parser.parse_args()
330 if args.verbose:
331 print("verbosity turned on")
332
333 And here goes:
334
335 .. code-block:: shell-session
336
337 $ python prog.py -v
338 verbosity turned on
339 $ python prog.py --help
340 usage: prog.py [-h] [-v]
341
342 options:
343 -h, --help show this help message and exit
344 -v, --verbose increase output verbosity
345
346 Note that the new ability is also reflected in the help text.
347
348
349 Combining Positional and Optional arguments
350 ===========================================
351
352 Our program keeps growing in complexity::
353
354 import argparse
355 parser = argparse.ArgumentParser()
356 parser.add_argument("square", type=int,
357 help="display a square of a given number")
358 parser.add_argument("-v", "--verbose", action="store_true",
359 help="increase output verbosity")
360 args = parser.parse_args()
361 answer = args.square**2
362 if args.verbose:
363 print(f"the square of {args.square} equals {answer}")
364 else:
365 print(answer)
366
367 And now the output:
368
369 .. code-block:: shell-session
370
371 $ python prog.py
372 usage: prog.py [-h] [-v] square
373 prog.py: error: the following arguments are required: square
374 $ python prog.py 4
375 16
376 $ python prog.py 4 --verbose
377 the square of 4 equals 16
378 $ python prog.py --verbose 4
379 the square of 4 equals 16
380
381 * We've brought back a positional argument, hence the complaint.
382
383 * Note that the order does not matter.
384
385 How about we give this program of ours back the ability to have
386 multiple verbosity values, and actually get to use them::
387
388 import argparse
389 parser = argparse.ArgumentParser()
390 parser.add_argument("square", type=int,
391 help="display a square of a given number")
392 parser.add_argument("-v", "--verbosity", type=int,
393 help="increase output verbosity")
394 args = parser.parse_args()
395 answer = args.square**2
396 if args.verbosity == 2:
397 print(f"the square of {args.square} equals {answer}")
398 elif args.verbosity == 1:
399 print(f"{args.square}^2 == {answer}")
400 else:
401 print(answer)
402
403 And the output:
404
405 .. code-block:: shell-session
406
407 $ python prog.py 4
408 16
409 $ python prog.py 4 -v
410 usage: prog.py [-h] [-v VERBOSITY] square
411 prog.py: error: argument -v/--verbosity: expected one argument
412 $ python prog.py 4 -v 1
413 4^2 == 16
414 $ python prog.py 4 -v 2
415 the square of 4 equals 16
416 $ python prog.py 4 -v 3
417 16
418
419 These all look good except the last one, which exposes a bug in our program.
420 Let's fix it by restricting the values the ``--verbosity`` option can accept::
421
422 import argparse
423 parser = argparse.ArgumentParser()
424 parser.add_argument("square", type=int,
425 help="display a square of a given number")
426 parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
427 help="increase output verbosity")
428 args = parser.parse_args()
429 answer = args.square**2
430 if args.verbosity == 2:
431 print(f"the square of {args.square} equals {answer}")
432 elif args.verbosity == 1:
433 print(f"{args.square}^2 == {answer}")
434 else:
435 print(answer)
436
437 And the output:
438
439 .. code-block:: shell-session
440
441 $ python prog.py 4 -v 3
442 usage: prog.py [-h] [-v {0,1,2}] square
443 prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
444 $ python prog.py 4 -h
445 usage: prog.py [-h] [-v {0,1,2}] square
446
447 positional arguments:
448 square display a square of a given number
449
450 options:
451 -h, --help show this help message and exit
452 -v, --verbosity {0,1,2}
453 increase output verbosity
454
455 Note that the change also reflects both in the error message as well as the
456 help string.
457
458 Now, let's use a different approach of playing with verbosity, which is pretty
459 common. It also matches the way the CPython executable handles its own
460 verbosity argument (check the output of ``python --help``)::
461
462 import argparse
463 parser = argparse.ArgumentParser()
464 parser.add_argument("square", type=int,
465 help="display the square of a given number")
466 parser.add_argument("-v", "--verbosity", action="count",
467 help="increase output verbosity")
468 args = parser.parse_args()
469 answer = args.square**2
470 if args.verbosity == 2:
471 print(f"the square of {args.square} equals {answer}")
472 elif args.verbosity == 1:
473 print(f"{args.square}^2 == {answer}")
474 else:
475 print(answer)
476
477 We have introduced another action, "count",
478 to count the number of occurrences of specific options.
479
480
481 .. code-block:: shell-session
482
483 $ python prog.py 4
484 16
485 $ python prog.py 4 -v
486 4^2 == 16
487 $ python prog.py 4 -vv
488 the square of 4 equals 16
489 $ python prog.py 4 --verbosity --verbosity
490 the square of 4 equals 16
491 $ python prog.py 4 -v 1
492 usage: prog.py [-h] [-v] square
493 prog.py: error: unrecognized arguments: 1
494 $ python prog.py 4 -h
495 usage: prog.py [-h] [-v] square
496
497 positional arguments:
498 square display a square of a given number
499
500 options:
501 -h, --help show this help message and exit
502 -v, --verbosity increase output verbosity
503 $ python prog.py 4 -vvv
504 16
505
506 * Yes, it's now more of a flag (similar to ``action="store_true"``) in the
507 previous version of our script. That should explain the complaint.
508
509 * It also behaves similar to "store_true" action.
510
511 * Now here's a demonstration of what the "count" action gives. You've probably
512 seen this sort of usage before.
513
514 * And if you don't specify the ``-v`` flag, that flag is considered to have
515 ``None`` value.
516
517 * As should be expected, specifying the long form of the flag, we should get
518 the same output.
519
520 * Sadly, our help output isn't very informative on the new ability our script
521 has acquired, but that can always be fixed by improving the documentation for
522 our script (e.g. via the ``help`` keyword argument).
523
524 * That last output exposes a bug in our program.
525
526
527 Let's fix::
528
529 import argparse
530 parser = argparse.ArgumentParser()
531 parser.add_argument("square", type=int,
532 help="display a square of a given number")
533 parser.add_argument("-v", "--verbosity", action="count",
534 help="increase output verbosity")
535 args = parser.parse_args()
536 answer = args.square**2
537
538 # bugfix: replace == with >=
539 if args.verbosity >= 2:
540 print(f"the square of {args.square} equals {answer}")
541 elif args.verbosity >= 1:
542 print(f"{args.square}^2 == {answer}")
543 else:
544 print(answer)
545
546 And this is what it gives:
547
548 .. code-block:: shell-session
549
550 $ python prog.py 4 -vvv
551 the square of 4 equals 16
552 $ python prog.py 4 -vvvv
553 the square of 4 equals 16
554 $ python prog.py 4
555 Traceback (most recent call last):
556 File "prog.py", line 11, in <module>
557 if args.verbosity >= 2:
558 TypeError: '>=' not supported between instances of 'NoneType' and 'int'
559
560
561 * First output went well, and fixes the bug we had before.
562 That is, we want any value >= 2 to be as verbose as possible.
563
564 * Third output not so good.
565
566 Let's fix that bug::
567
568 import argparse
569 parser = argparse.ArgumentParser()
570 parser.add_argument("square", type=int,
571 help="display a square of a given number")
572 parser.add_argument("-v", "--verbosity", action="count", default=0,
573 help="increase output verbosity")
574 args = parser.parse_args()
575 answer = args.square**2
576 if args.verbosity >= 2:
577 print(f"the square of {args.square} equals {answer}")
578 elif args.verbosity >= 1:
579 print(f"{args.square}^2 == {answer}")
580 else:
581 print(answer)
582
583 We've just introduced yet another keyword, ``default``.
584 We've set it to ``0`` in order to make it comparable to the other int values.
585 Remember that by default,
586 if an optional argument isn't specified,
587 it gets the ``None`` value, and that cannot be compared to an int value
588 (hence the :exc:`TypeError` exception).
589
590 And:
591
592 .. code-block:: shell-session
593
594 $ python prog.py 4
595 16
596
597 You can go quite far just with what we've learned so far,
598 and we have only scratched the surface.
599 The :mod:`argparse` module is very powerful,
600 and we'll explore a bit more of it before we end this tutorial.
601
602
603 Getting a little more advanced
604 ==============================
605
606 What if we wanted to expand our tiny program to perform other powers,
607 not just squares::
608
609 import argparse
610 parser = argparse.ArgumentParser()
611 parser.add_argument("x", type=int, help="the base")
612 parser.add_argument("y", type=int, help="the exponent")
613 parser.add_argument("-v", "--verbosity", action="count", default=0)
614 args = parser.parse_args()
615 answer = args.x**args.y
616 if args.verbosity >= 2:
617 print(f"{args.x} to the power {args.y} equals {answer}")
618 elif args.verbosity >= 1:
619 print(f"{args.x}^{args.y} == {answer}")
620 else:
621 print(answer)
622
623 Output:
624
625 .. code-block:: shell-session
626
627 $ python prog.py
628 usage: prog.py [-h] [-v] x y
629 prog.py: error: the following arguments are required: x, y
630 $ python prog.py -h
631 usage: prog.py [-h] [-v] x y
632
633 positional arguments:
634 x the base
635 y the exponent
636
637 options:
638 -h, --help show this help message and exit
639 -v, --verbosity
640 $ python prog.py 4 2 -v
641 4^2 == 16
642
643
644 Notice that so far we've been using verbosity level to *change* the text
645 that gets displayed. The following example instead uses verbosity level
646 to display *more* text instead::
647
648 import argparse
649 parser = argparse.ArgumentParser()
650 parser.add_argument("x", type=int, help="the base")
651 parser.add_argument("y", type=int, help="the exponent")
652 parser.add_argument("-v", "--verbosity", action="count", default=0)
653 args = parser.parse_args()
654 answer = args.x**args.y
655 if args.verbosity >= 2:
656 print(f"Running '{__file__}'")
657 if args.verbosity >= 1:
658 print(f"{args.x}^{args.y} == ", end="")
659 print(answer)
660
661 Output:
662
663 .. code-block:: shell-session
664
665 $ python prog.py 4 2
666 16
667 $ python prog.py 4 2 -v
668 4^2 == 16
669 $ python prog.py 4 2 -vv
670 Running 'prog.py'
671 4^2 == 16
672
673
674 .. _specifying-ambiguous-arguments:
675
676 Specifying ambiguous arguments
677 ------------------------------
678
679 When there is ambiguity in deciding whether an argument is positional or for an
680 argument, ``--`` can be used to tell :meth:`~ArgumentParser.parse_args` that
681 everything after that is a positional argument::
682
683 >>> parser = argparse.ArgumentParser(prog='PROG')
684 >>> parser.add_argument('-n', nargs='+')
685 >>> parser.add_argument('args', nargs='*')
686
687 >>> # ambiguous, so parse_args assumes it's an option
688 >>> parser.parse_args(['-f'])
689 usage: PROG [-h] [-n N [N ...]] [args ...]
690 PROG: error: unrecognized arguments: -f
691
692 >>> parser.parse_args(['--', '-f'])
693 Namespace(args=['-f'], n=None)
694
695 >>> # ambiguous, so the -n option greedily accepts arguments
696 >>> parser.parse_args(['-n', '1', '2', '3'])
697 Namespace(args=[], n=['1', '2', '3'])
698
699 >>> parser.parse_args(['-n', '1', '--', '2', '3'])
700 Namespace(args=['2', '3'], n=['1'])
701
702
703 Conflicting options
704 -------------------
705
706 So far, we have been working with two methods of an
707 :class:`argparse.ArgumentParser` instance. Let's introduce a third one,
708 :meth:`~ArgumentParser.add_mutually_exclusive_group`. It allows for us to specify options that
709 conflict with each other. Let's also change the rest of the program so that
710 the new functionality makes more sense:
711 we'll introduce the ``--quiet`` option,
712 which will be the opposite of the ``--verbose`` one::
713
714 import argparse
715
716 parser = argparse.ArgumentParser()
717 group = parser.add_mutually_exclusive_group()
718 group.add_argument("-v", "--verbose", action="store_true")
719 group.add_argument("-q", "--quiet", action="store_true")
720 parser.add_argument("x", type=int, help="the base")
721 parser.add_argument("y", type=int, help="the exponent")
722 args = parser.parse_args()
723 answer = args.x**args.y
724
725 if args.quiet:
726 print(answer)
727 elif args.verbose:
728 print(f"{args.x} to the power {args.y} equals {answer}")
729 else:
730 print(f"{args.x}^{args.y} == {answer}")
731
732 Our program is now simpler, and we've lost some functionality for the sake of
733 demonstration. Anyways, here's the output:
734
735 .. code-block:: shell-session
736
737 $ python prog.py 4 2
738 4^2 == 16
739 $ python prog.py 4 2 -q
740 16
741 $ python prog.py 4 2 -v
742 4 to the power 2 equals 16
743 $ python prog.py 4 2 -vq
744 usage: prog.py [-h] [-v | -q] x y
745 prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
746 $ python prog.py 4 2 -v --quiet
747 usage: prog.py [-h] [-v | -q] x y
748 prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
749
750 That should be easy to follow. I've added that last output so you can see the
751 sort of flexibility you get, i.e. mixing long form options with short form
752 ones.
753
754 Before we conclude, you probably want to tell your users the main purpose of
755 your program, just in case they don't know::
756
757 import argparse
758
759 parser = argparse.ArgumentParser(description="calculate X to the power of Y")
760 group = parser.add_mutually_exclusive_group()
761 group.add_argument("-v", "--verbose", action="store_true")
762 group.add_argument("-q", "--quiet", action="store_true")
763 parser.add_argument("x", type=int, help="the base")
764 parser.add_argument("y", type=int, help="the exponent")
765 args = parser.parse_args()
766 answer = args.x**args.y
767
768 if args.quiet:
769 print(answer)
770 elif args.verbose:
771 print(f"{args.x} to the power {args.y} equals {answer}")
772 else:
773 print(f"{args.x}^{args.y} == {answer}")
774
775 Note that slight difference in the usage text. Note the ``[-v | -q]``,
776 which tells us that we can either use ``-v`` or ``-q``,
777 but not both at the same time:
778
779 .. code-block:: shell-session
780
781 $ python prog.py --help
782 usage: prog.py [-h] [-v | -q] x y
783
784 calculate X to the power of Y
785
786 positional arguments:
787 x the base
788 y the exponent
789
790 options:
791 -h, --help show this help message and exit
792 -v, --verbose
793 -q, --quiet
794
795
796 How to translate the argparse output
797 ====================================
798
799 The output of the :mod:`argparse` module such as its help text and error
800 messages are all made translatable using the :mod:`gettext` module. This
801 allows applications to easily localize messages produced by
802 :mod:`argparse`. See also :ref:`i18n-howto`.
803
804 For instance, in this :mod:`argparse` output:
805
806 .. code-block:: shell-session
807
808 $ python prog.py --help
809 usage: prog.py [-h] [-v | -q] x y
810
811 calculate X to the power of Y
812
813 positional arguments:
814 x the base
815 y the exponent
816
817 options:
818 -h, --help show this help message and exit
819 -v, --verbose
820 -q, --quiet
821
822 The strings ``usage:``, ``positional arguments:``, ``options:`` and
823 ``show this help message and exit`` are all translatable.
824
825 In order to translate these strings, they must first be extracted
826 into a ``.po`` file. For example, using `Babel <https://babel.pocoo.org/>`__,
827 run this command:
828
829 .. code-block:: shell-session
830
831 $ pybabel extract -o messages.po /usr/lib/python3.12/argparse.py
832
833 This command will extract all translatable strings from the :mod:`argparse`
834 module and output them into a file named ``messages.po``. This command assumes
835 that your Python installation is in ``/usr/lib``.
836
837 You can find out the location of the :mod:`argparse` module on your system
838 using this script::
839
840 import argparse
841 print(argparse.__file__)
842
843 Once the messages in the ``.po`` file are translated and the translations are
844 installed using :mod:`gettext`, :mod:`argparse` will be able to display the
845 translated messages.
846
847 To translate your own strings in the :mod:`argparse` output, use :mod:`gettext`.
848
849 Custom type converters
850 ======================
851
852 The :mod:`argparse` module allows you to specify custom type converters for
853 your command-line arguments. This allows you to modify user input before it's
854 stored in the :class:`argparse.Namespace`. This can be useful when you need to
855 pre-process the input before it is used in your program.
856
857 When using a custom type converter, you can use any callable that takes a
858 single string argument (the argument value) and returns the converted value.
859 However, if you need to handle more complex scenarios, you can use a custom
860 action class with the **action** parameter instead.
861
862 For example, let's say you want to handle arguments with different prefixes and
863 process them accordingly::
864
865 import argparse
866
867 parser = argparse.ArgumentParser(prefix_chars='-+')
868
869 parser.add_argument('-a', metavar='<value>', action='append',
870 type=lambda x: ('-', x))
871 parser.add_argument('+a', metavar='<value>', action='append',
872 type=lambda x: ('+', x))
873
874 args = parser.parse_args()
875 print(args)
876
877 Output:
878
879 .. code-block:: shell-session
880
881 $ python prog.py -a value1 +a value2
882 Namespace(a=[('-', 'value1'), ('+', 'value2')])
883
884 In this example, we:
885
886 * Created a parser with custom prefix characters using the ``prefix_chars``
887 parameter.
888
889 * Defined two arguments, ``-a`` and ``+a``, which used the ``type`` parameter to
890 create custom type converters to store the value in a tuple with the prefix.
891
892 Without the custom type converters, the arguments would have treated the ``-a``
893 and ``+a`` as the same argument, which would have been undesirable. By using custom
894 type converters, we were able to differentiate between the two arguments.
895
896 Conclusion
897 ==========
898
899 The :mod:`argparse` module offers a lot more than shown here.
900 Its docs are quite detailed and thorough, and full of examples.
901 Having gone through this tutorial, you should easily digest them
902 without feeling overwhelmed.