Argparse Function with Command-Line Options

  • Share this:

Code introduction


This code defines a Python function using the Argparse library, which allows users to enable options, set integer values, and make choices through command-line arguments.


Technology Stack : The code uses the Argparse library and Python programming language.

Code Type : The type of code

Code Difficulty :


                
                    
import argparse
import random

def random_argparse_function():
    parser = argparse.ArgumentParser(description='A random function using Argparse')
    parser.add_argument('--option1', action='store_true', help='Enable option 1')
    parser.add_argument('--option2', type=int, default=42, help='Set option 2 value, default is 42')
    parser.add_argument('--option3', choices=['a', 'b', 'c'], help='Choose between a, b, or c for option 3')
    args = parser.parse_args()

    if args.option1:
        print("Option 1 is enabled")
    if args.option2:
        print(f"Option 2 value is {args.option2}")
    if args.option3:
        print(f"Option 3 choice is {args.option3}")