Agile Automation avatar

Python Tips: MORE Parsing arguments for your application

agileautomation

Published: 28 Dec 2023 › Updated: 28 Dec 2023Python Tips: MORE Parsing arguments for your application

Python Tips: MORE Parsing arguments for your application

There is so much more you can do with arguments to your python scripts here are a few more ideas.

This sample below outlines a couple new things, positional arguments, app description and boolean switches to simply enable or disable features.

import argparse

# Create the parser and include an app description for it when you open the script with -h for help
parser = argparse.ArgumentParser(description='Your app description')

# Add arguments
parser.add_argument('pos_arg', type=int, help='A required integer positional argument')
parser.add_argument('--opt_arg', type=int, default=10, help='An optional integer argument')
parser.add_argument('--switch', action='store_true', help='A boolean switch')

# Parse the arguments
args = parser.parse_args()

# Access the values
print(args.pos_arg)
print(args.opt_arg)
print(args.switch)

Here is a way you can then also use specific validation for the types on your arguments. Like setting a range for your input values that you allow

import argparse

def ranged_num(lowest=-1, highest=1):
   """Check a numeric is in expected range."""
   def type_func(a_value):
       a_value = int(a_value) # or "float"; you could also have error handling here
       if not (a_value >= lowest and a_value <= highest): # I'd rewrite this to an "or"
           raise argparse.ArgumentTypeError("Not in range.")
       return a_value
   return type_func

parser = argparse.ArgumentParser()
parser.add_argument('num', type=ranged_num(), help='A number in range [-1,1]')
args = parser.parse_args()

print(args.num)

Actually you can add more than just a description, also a program name and footer in the help.

parser = argparse.ArgumentParser(
                    prog='ProgramName',
                    description='What the program does',
                    epilog='Text at the bottom of help')

Python will automatically generate your -h help for you based on all these arguments you've setup. NICE!

python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
 N           an integer for the accumulator

options:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)

Leave Python Tips: MORE Parsing arguments for your application to:

Written by

A software consultant specializing in control systems, automation and data collection. Python Development and tips.

Read more #python posts


Best Posts From Agile Automation

We have not curated any of agileautomation's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Agile Automation