Skip to content

Commit dcc53eb

Browse files
miss-islingtonmental32
authored andcommitted
bpo-37726: Prefer argparse over getopt in stdlib tutorial (GH-15052) (#15070)
(cherry picked from commit 2491134) Co-authored-by: mental <[email protected]>
1 parent 462f070 commit dcc53eb

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

Doc/tutorial/stdlib.rst

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,21 @@ three`` at the command line::
7272
>>> print(sys.argv)
7373
['demo.py', 'one', 'two', 'three']
7474

75-
The :mod:`getopt` module processes *sys.argv* using the conventions of the Unix
76-
:func:`getopt` function. More powerful and flexible command line processing is
77-
provided by the :mod:`argparse` module.
78-
75+
The :mod:`argparse` module provides a mechanism to process command line arguments.
76+
It should always be preferred over directly processing ``sys.argv`` manually.
77+
78+
Take, for example, the below snippet of code::
79+
80+
>>> import argparse
81+
>>> from getpass import getuser
82+
>>> parser = argparse.ArgumentParser(description='An argparse example.')
83+
>>> parser.add_argument('name', nargs='?', default=getuser(), help='The name of someone to greet.')
84+
>>> parser.add_argument('--verbose', '-v', action='count')
85+
>>> args = parser.parse_args()
86+
>>> greeting = ["Hi", "Hello", "Greetings! its very nice to meet you"][args.verbose % 3]
87+
>>> print(f'{greeting}, {args.name}')
88+
>>> if not args.verbose:
89+
>>> print('Try running this again with multiple "-v" flags!')
7990

8091
.. _tut-stderr:
8192

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Stop recommending getopt in the tutorial for command line argument parsing
2+
and promote argparse.

0 commit comments

Comments
 (0)