Pragmatism in the real world

Parsing command line arguments in Python

This is one of those posts that I write so that I can look it up again as this information is all over the Internet, but it took me a little while to find what I was looking for.

To accept command line arguments in a Python script, use the argparse package:

import argparse

You can then instantiate a parser and add arguments you want to accept:

parser = argparse.ArgumentParser(description="Convert a JSON array to JSONL format")

parser.add_argument("filename", help="Filename of JSON file to convert")

To read the arguments, call parse_args():

args = parser.parse_args()

The values provided by the user are properties on args:

in_filename = args.filename

Rather helpfully, if the filename is not provided, we get a useful error message:

$ uv run convert_to_jsonl.py 
usage: convert_to_jsonl [-h] filename
convert_to_jsonl: error: the following arguments are required: filename

You also get built-in help:

$ uv run convert_to_jsonl.py -h
usage: convert_to_jsonl.py [-h] filename

Convert a JSON array to JSONL format

positional arguments:
  filename    Filename of JSON file to convert

options:
  -h, --help  show this help message and exit

Super simple to use. I just need to remember that it exists!

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *