Random Argparse Function: Parsing CLI Args

  • Share this:

Code introduction


This function uses the Argparse library to parse command-line arguments, accepting an integer, a string, and a boolean value, and outputs the corresponding values or status.


Technology Stack : Argparse, command-line argument parsing

Code Type : Function

Code Difficulty : Advanced


                
                    
import argparse
import random

def random_argparse_function():
    parser = argparse.ArgumentParser(description="Random Function")
    parser.add_argument('--number', type=int, help='An integer number')
    parser.add_argument('--string', type=str, help='A string value')
    parser.add_argument('--boolean', action='store_true', help='A boolean flag')

    args = parser.parse_args()

    if args.number:
        print(f"The number is {args.number}")
    if args.string:
        print(f"The string is '{args.string}'")
    if args.boolean:
        print("The boolean flag is set")