| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
1 parent 0d30ae1 commit 2491134
2 files changed
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -72,10 +72,21 @@ three`` at the command line:: | |||
| 72 | 72 | >>> print(sys.argv) | |
| 73 | 73 | ['demo.py', 'one', 'two', 'three'] | |
| 74 | 74 | ||
| 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!') | ||
| 79 | 90 | ||
| 80 | 91 | .. _tut-stderr: | |
| 81 | 92 | ||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -0,0 +1,2 @@ | |||
| 1 | + Stop recommending getopt in the tutorial for command line argument parsing | ||
| 2 | + and promote argparse. | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments