Python Tips: MORE Parsing arguments for your application

in #pythonlast year

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)
Sort:  

Congratulations @agileautomation! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You received more than 10 upvotes.
Your next target is to reach 50 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

Hive Power Up Day - January 1st 2024

@agileautomation, thank you for supporting the HiveBuzz project by voting for our witness.

Here Is a small present to show our gratitude
Click on the badge to view your board.

Once again, thanks for your support!

Check out our last posts:

Hive Power Up Day - January 1st 2024