4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

Python Tips: MORE Parsing arguments for your application

https://snipboard.io/ALgh1m.jpg

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)
4 upvotes $0.03

Replies (2)

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: