Explain Codes LogoExplain Codes Logo

Simple argparse example wanted: 1 argument, 3 results

python
argparse
command-line
input-validation
Anton ShumikhinbyAnton Shumikhin·Aug 7, 2024
TLDR

For a quick start, here's a simple argparse example. An integer argument is processed to provide three distinct outcomes:

import argparse # Define a function that takes an integer and returns three distinct outputs def process_arg(value): return value ** 2, value + 10, value / 2 # Create a parser parser = argparse.ArgumentParser() # Define the argument parser.add_argument('num', type=int, help='Input an integer to explore the magic of numbers') # Parse the argument args = parser.parse_args() # Process the argument and store the results result1, result2, result3 = process_arg(args.num) # Print out the results print(f'Squared: {result1}, Incremented by 10: {result2}, Halved: {result3}')

Running this script from the command line, like python scriptname.py 4, it interprets ‘4’ as the ‘num’ input.

Advanced argparse handling techniques

The above script is good for a quick start, but argparse is a much more powerful beast. Let's delve deeper.

Custom validation of argument values

You may need to validate argument inputs against specific conditions. Here we validate if the provided argument is a positive integer:

import argparse def check_positive(value): ivalue = int(value) # Let's be like a strict math teacher demanding positive integers only if ivalue <= 0: raise argparse.ArgumentTypeError("%s is not positive. You've been a naughty number!" % value) return ivalue parser = argparse.ArgumentParser() parser.add_argument('num', type=check_positive) args = parser.parse_args()

Handling different types

Argparse lets you handle different argument types with flexibility. Let's process an integer, list, or string differently:

import argparse # Define a simple parser, a friendly bouncer validating your inputs at the club parser = argparse.ArgumentParser() # Add the argument which could take different forms - just like a secret agent parser.add_argument('input', help='Input an integer, list, or string to understand its hidden power') # Parse the secret agent-like argument and reveal its true identity args = parser.parse_args() # Determine and print the type of the argument if args.input.isdigit(): # OK, you're a number? Let's square you. result = int(args.input) ** 2 elif args.input.startswith('[') and args.input.endswith(']'): # If you're a list, let's sum things up! input_list = list(map(int, args.input.strip('[]').split(','))) result = sum(input_list) else: # You look like a string, just uppercase you to make sure you scream loud result = args.input.upper() print(result)

The ins and outs of argparse

Argparse doesn't stop impressing us with its power and versatility. Let's explore more.

Implicit argument type conversion

Argparse can automatically convert the argument type using the type parameter of add_argument(). This saves you from repeatedly writing int(my_argument) in your code.

Handling boolean flags

American football is not the only place where flags matter. argparse makes handling boolean flags a breeze with action='store_true':

parser.add_argument('--flag', action='store_true', help='I am a simple flag. Flip me if you dare!')

Now args.flag will give you True if --flag is used in the command line, and False otherwise.

Improve the visual hierarchy and logical grouping of your argument structure, very much like how it's convenient to have all dairy products located in one aisle in your local supermarket:

# Nitrogen, Phosphorus, and Potassium for your growing script group = parser.add_argument_group('Group Name') # A member of the productive group group.add_argument('--option', type=int, help='An integer - the favorite option of this group')

Troubleshooting and best practices

Named vs positional arguments

Remember: Positional arguments are unnamed but mandatory, while named arguments (starting with - or --) are optional.

Enlightening help messages

Help your future self and fellow coders by always defining a useful help message while adding each argument. Do they know what you were thinking while writing the script? Probably not!

Consistent argument naming

Keeping argument names consistently either snake_case or camelCase avoids confusion and keeps your script neat and orderly as a German Innenhof (inner courtyard).

Cooking without burning: test your inputs

Just like in cooking, always taste your dish (test your script) before serving (sharing with others). Catch and handle edge cases, and always display a friendly message for invalid inputs.