import argparse
import logging
def paginate_cli_args(parser, args, results_generator, page_size=10):
"""
Paginates results from a generator based on CLI arguments.
Args:
parser: argparse.ArgumentParser object.
args: argparse.Namespace object containing CLI arguments.
results_generator: A generator function that yields results.
page_size: The number of results per page.
"""
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
try:
page = args.page if hasattr(args, 'page') else 1 # Default to page 1 if not specified
total_results = sum(1 for _ in results_generator) #Count total results
if total_results == 0:
logging.info("No results found.")
return
start = (page - 1) * page_size
end = start + page_size
for i, result in enumerate(results_generator):
if i >= start and i < end:
logging.debug(f"Processing result {i+1}/{total_results}")
yield result
elif i >= end:
logging.info(f"Finished processing page {page}.")
break #Stop if end of results is reached
except Exception as e:
logging.error(f"An error occurred during pagination: {e}")
raise
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Paginate CLI arguments.")
parser.add_argument("--page", type=int, help="Page number to retrieve.")
# Example results generator
def example_results(n):
for i in range(n):
yield f"Result {i+1}"
args = parser.parse_args()
try:
paginated_results = list(paginate_cli_args(parser, args, example_results(25), page_size=5)) #Example Usage
for result in paginated_results:
print(result)
except Exception as e:
print(f"Error: {e}")
Add your comment