Last active
August 15, 2022 20:30
-
-
Save Microflame/b571cccba4ab434bbcf8187a2c9b3bfa to your computer and use it in GitHub Desktop.
Example usage of Python argparse module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import argparse | |
| parser = argparse.ArgumentParser(description='App description') | |
| # Named Argument | |
| parser.add_argument('-f', '--foo') | |
| # ./exe -f bar OR ./exe --foo bar | |
| # foo -> bar | |
| # Positional Argument | |
| parser.add_argument('foo') | |
| # ./exe bar | |
| # foo -> bar | |
| # Generic Switch | |
| parser.add_argument('--foo', action='store_const', const=42) | |
| # ./exe --foo | |
| # foo -> 42 | |
| # Bool Switch | |
| parser.add_argument('--foo', action='store_true') | |
| # ./exe --foo | |
| # foo -> True | |
| # Argument List | |
| parser.add_argument('--foo', nargs='3') | |
| # OR nargs='*' OR nargs='+' | |
| # Default | |
| parser.add_argument('--foo', default=42) | |
| # ./exe | |
| # foo -> 42 | |
| # Type | |
| parser.add_argument('--foo', type=int) | |
| # Choices | |
| parser.add_argument('--foo', choices=['bar', 'baz']) | |
| # ./exe --foo bar | |
| # foo -> bar | |
| # Required | |
| parser.add_argument('--foo', required=True) | |
| # Help | |
| parser.add_argument('--foo', help='Foo variable') | |
| # ./exe --foo bar | |
| parsed_args = parser.parse_args() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment