Skip to content

Instantly share code, notes, and snippets.

@Microflame
Last active August 15, 2022 20:30
Show Gist options
  • Select an option

  • Save Microflame/b571cccba4ab434bbcf8187a2c9b3bfa to your computer and use it in GitHub Desktop.

Select an option

Save Microflame/b571cccba4ab434bbcf8187a2c9b3bfa to your computer and use it in GitHub Desktop.
Example usage of Python argparse module
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