Code for How to Use the Argparse Module in Python Tutorial


View on Github

1_simple_example.py

import argparse

parser = argparse.ArgumentParser(description='A simple argparse example.')
parser.add_argument('input', help='Input file to process.')

args = parser.parse_args()
print(f'Processing file: {args.input}')

2.2_default_and_required.py

import argparse

parser = argparse.ArgumentParser(description='A simple argparse example.')
parser.add_argument('input', help='Input file to process.')
# parser.add_argument('-o', '--output', default='output.txt', help='Output file.')
parser.add_argument('-o', '--output', required=True, help='Output file.')

args = parser.parse_args()
print(f'Processing file: {args.input}')
print(f"Writing to file: {args.output}")

2.3_choices.py

import argparse

parser = argparse.ArgumentParser(description='A simple argparse example.')
parser.add_argument('input', help='Input file to process.')
parser.add_argument('-m', '--mode', choices=['add', 'subtract', 'multiply', 'divide'], help='Calculation mode.')

args = parser.parse_args()
print(f'Processing file: {args.input}')
print(f"Mode: {args.mode}")

2.5_nargs.py

import argparse

parser = argparse.ArgumentParser(description='A simple argparse example.')
parser.add_argument('--values', nargs=3)
# parser.add_argument('--value', nargs='?', default='default_value')
# parser.add_argument('--values', nargs='*')
# parser.add_argument('--values', nargs='+')

args = parser.parse_args()
print(f"Values: {args.values}")

2.6_builtin_actions.py

import argparse

parser = argparse.ArgumentParser(description='A simple argparse example.')
parser.add_argument('--foo', action='store', help='Store the value of foo.')
parser.add_argument('--enable', action='store_true', help='Enable the feature.')
parser.add_argument('--disable', action='store_false', help='Disable the feature.')
parser.add_argument('--level', action='store_const', const='advanced', help='Set level to advanced.')
parser.add_argument('--values', action='append', help='Append values to a list.')
parser.add_argument('--add_const', action='append_const', const=42, help='Add 42 to the list.')
parser.add_argument('-v', '--verbose', action='count', help='Increase verbosity level.')
args = parser.parse_args()
print(f"Values: {args.values}")
print(f"Verbosity: {args.verbose}")

2.6_custom_actions.py

import argparse

class CustomAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        # Perform custom processing on the argument values
        processed_values = [value.upper() for value in values]

        # Set the attribute on the namespace object
        setattr(namespace, self.dest, processed_values)

# Set up argument parser and add the custom action
parser = argparse.ArgumentParser(description='Custom argument action example.')
parser.add_argument('-n', '--names', nargs='+', action=CustomAction, help='A list of names to be processed.')

args = parser.parse_args()
print(args.names)

2.7_argument_types.py

import argparse

parser = argparse.ArgumentParser(description='A simple argparse example.')
parser.add_argument("-r", "--ratio", type=float)
args = parser.parse_args()
print(f"Ratio: {args.ratio}")

3.3_subcommand_example.py

import argparse

parser = argparse.ArgumentParser(description='A subcommand example.')
subparsers = parser.add_subparsers(help='Subcommand help')

list_parser = subparsers.add_parser('list', help='List items')
add_parser = subparsers.add_parser('add', help='Add an item')
add_parser.add_argument('item', help='Item to add')

args = parser.parse_args()

4.1_file_renamer.py

import argparse
import os

# Rename function
def rename_files(args):
    # Your file renaming logic here
    print(f"Renaming files in {args.path}...")
    print(f"Prefix: {args.prefix}")
    print(f"Suffix: {args.suffix}")
    print(f"Replace: {args.replace}")
    os.chdir(args.path)
    for file in os.listdir():
        # Get the file name and extension
        file_name, file_ext = os.path.splitext(file)
        # Add prefix
        if args.prefix:
            file_name = f"{args.prefix}{file_name}"
        # Add suffix
        if args.suffix:
            file_name = f"{file_name}{args.suffix}"
        # Replace substring
        if args.replace:
            file_name = file_name.replace(args.replace[0], args.replace[1])
        # Rename the file
        print(f"Renaming {file} to {file_name}{file_ext}")
        os.rename(file, f"{file_name}{file_ext}")
        
# custom type for checking if a path exists
def path_exists(path):
    if os.path.exists(path):
        return path
    else:
        raise argparse.ArgumentTypeError(f"Path {path} does not exist.")
    
    
# Set up argument parser
parser = argparse.ArgumentParser(description='File renaming tool.')
parser.add_argument('path', type=path_exists, help='Path to the folder containing the files to rename.')
parser.add_argument('-p', '--prefix', help='Add a prefix to each file name.')
parser.add_argument('-s', '--suffix', help='Add a suffix to each file name.')
parser.add_argument('-r', '--replace', nargs=2, help='Replace a substring in each file name. Usage: -r old_string new_string')

args = parser.parse_args()

# Call the renaming function
rename_files(args)

4.2_simple_calculator.py

import argparse

# Operation functions
def add(args):
    print(args.x + args.y)

def subtract(args):
    print(args.x - args.y)

def multiply(args):
    print(args.x * args.y)

def divide(args):
    print(args.x / args.y)

# Set up argument parser
parser = argparse.ArgumentParser(description='Command-line calculator.')
subparsers = parser.add_subparsers()

# Add subcommands
add_parser = subparsers.add_parser('add', help='Add two numbers.')
add_parser.add_argument('x', type=float, help='First number.')
add_parser.add_argument('y', type=float, help='Second number.')
add_parser.set_defaults(func=add)

subtract_parser = subparsers.add_parser('subtract', help='Subtract two numbers.')
subtract_parser.add_argument('x', type=float, help='First number.')
subtract_parser.add_argument('y', type=float, help='Second number.')
subtract_parser.set_defaults(func=subtract)

multiply_parser = subparsers.add_parser('multiply', help='Multiply two numbers.')
multiply_parser.add_argument('x', type=float, help='First number.')
multiply_parser.add_argument('y', type=float, help='Second number.')
multiply_parser.set_defaults(func=multiply)

divide_parser = subparsers.add_parser('divide', help='Divide two numbers.')
divide_parser.add_argument('x', type=float, help='First number.')
divide_parser.add_argument('y', type=float, help='Second number.')
divide_parser.set_defaults(func=divide)

args = parser.parse_args()
args.func(args)


pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy