Back to cheatsheets

Python

Parse argument in Python

To parse arguments in Python 3, you can use the argparse module. This module makes it easy to write user-friendly command-line interfaces.

Here is a simple example of how to use argparse to parse arguments in a Python 3 script:

import argparse
 
parser = argparse.ArgumentParser()
parser.add_argument('--input', required=True, help='The input file to process')
parser.add_argument('--output', required=True, help='The output file to write to')
parser.add_argument('--verbose', action='store_true', help='Print verbose output')
 
args = parser.parse_args()
 
# Now you can access the parsed arguments using the `args` namespace
with open(args.input, 'r') as f_in, open(args.output, 'w') as f_out:
  for line in f_in:
    # process the line
    if args.verbose:
      print(line)
    f_out.write(line)

This script expects the --input and --output arguments to be passed in when it is run. It also accepts an optional --verbose flag that, if provided, will cause the script to print verbose output.

To run this script and parse its arguments, you would use the following command:

python script.py --input input.txt --output output.txt

You can also provide the --verbose flag to enable verbose output:

python script.py --input input.txt --output output.txt --verbose

For more information about the argparse module, you can consult the official Python documentation.