> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/language/python/library/argparse.md).

# argparse

`argparse` in Python is a powerful library for building command-line interfaces (CLIs). It simplifies the task of creating and handling command-line arguments, enabling users to provide inputs dynamically when running scripts.

***

### **Overview**

1. Define what arguments your program requires.
2. Parse command-line arguments automatically.
3. Generate helpful usage and error messages.

#### **Key Components**

1. **ArgumentParser**: The main class for handling arguments.
2. **add\_argument()**: Method to define the arguments your program accepts.
3. **parse\_args()**: Method to process and retrieve the parsed arguments.

***

### **`ArgumentParser` Constructor Parameters**

The `ArgumentParser` class defines the CLI behavior. Here are all its parameters:

| **Parameter**           | **Description**                                                                                 | **Default**              |
| ----------------------- | ----------------------------------------------------------------------------------------------- | ------------------------ |
| `prog`                  | Program name (overrides the default, which is the script name).                                 | `sys.argv[0]`            |
| `usage`                 | Custom usage message displayed in help or error messages.                                       | Auto-generated usage     |
| `description`           | Description of what the program does, displayed in the help message before the argument list.   | `None`                   |
| `epilog`                | Text displayed after the argument help section in the help message.                             | `None`                   |
| `parents`               | A list of other `ArgumentParser` objects whose arguments should also be included.               | `[]`                     |
| `formatter_class`       | Controls help message formatting. Common options:                                               | `argparse.HelpFormatter` |
|                         | - `RawDescriptionHelpFormatter` (preserves newlines).                                           |                          |
|                         | - `ArgumentDefaultsHelpFormatter` (shows default values).                                       |                          |
| `prefix_chars`          | Characters used to prefix optional arguments (e.g., `-` or `/`).                                | `'-'`                    |
| `fromfile_prefix_chars` | Characters that indicate a file containing arguments (e.g., `@`).                               | `None`                   |
| `argument_default`      | Global default value for arguments (overrides `None`).                                          | `None`                   |
| `conflict_handler`      | Resolves argument conflicts (`'error'` or `'resolve'`).                                         | `'error'`                |
| `add_help`              | If `True`, adds the `-h/--help` argument automatically.                                         | `True`                   |
| `allow_abbrev`          | If `True`, allows abbreviated forms of long options.                                            | `True`                   |
| `exit_on_error`         | If `False`, raises exceptions instead of exiting on argument errors (introduced in Python 3.9). | `True`                   |

***

### **`add_argument` Parameters**

The `add_argument` method defines what arguments your program accepts. It has the following parameters:

| **Parameter**   | **Description**                                                                                        | **Default**  |
| --------------- | ------------------------------------------------------------------------------------------------------ | ------------ |
| `name_or_flags` | Positional argument name or optional flags (e.g., `'input_file'`, `'-v'`, `'--verbose'`).              | **Required** |
| `action`        | Action to take when the argument is parsed:                                                            | `'store'`    |
|                 | - `'store'`: Save the provided value (default).                                                        |              |
|                 | - `'store_true'`: Save `True` if the flag is present (for booleans).                                   |              |
|                 | - `'store_false'`: Save `False` if the flag is present (for booleans).                                 |              |
|                 | - `'append'`: Add values to a list.                                                                    |              |
|                 | - `'count'`: Count occurrences of the flag.                                                            |              |
|                 | - Custom action class.                                                                                 |              |
| `nargs`         | Number of arguments to accept (e.g., `1`, `'?'`, `'*'`, `'+'`).                                        | `None`       |
| `const`         | A constant value assigned if the argument is used without a value (used with `nargs='?'` or `action`). | `None`       |
| `default`       | Default value if the argument is not provided.                                                         | `None`       |
| `type`          | The type to convert the argument to (e.g., `int`, `float`, `str`, or a custom callable).               | `str`        |
| `choices`       | A list of valid values for the argument (e.g., `[1, 2, 3]`).                                           | `None`       |
| `required`      | If `True`, makes the argument mandatory (only for optional arguments).                                 | `False`      |
| `help`          | A brief description of what the argument does (displayed in help messages).                            | `None`       |
| `metavar`       | Custom name for the argument in usage and help messages.                                               | `None`       |
| `dest`          | The name of the attribute to store the value in (`args.dest`).                                         | `None`       |

***

### **Using `argparse`**

Here’s a practical example of how to use `argparse`:

```python
import argparse

# Create a parser object
parser = argparse.ArgumentParser(
    prog="example_program",
    usage="example_program [options] input_file",
    description="This program demonstrates argparse usage.",
    epilog="Thank you for using example_program!",
)

# Define arguments
parser.add_argument(
    'input_file',  # Positional argument
    type=str,
    help="The input file to process."
)
parser.add_argument(
    '-v', '--verbose',  # Optional argument
    action='store_true',
    help="Enable verbose mode."
)
parser.add_argument(
    '--level',  # Optional argument with choices
    type=int,
    choices=[1, 2, 3],
    default=1,
    help="Set the processing level (1, 2, or 3). Default is 1."
)

# Parse arguments
args = parser.parse_args()

# Access arguments
print(f"Input File: {args.input_file}")
print(f"Verbose Mode: {args.verbose}")
print(f"Processing Level: {args.level}")
```

***

### **Features Summary**

#### **Positional Arguments**

* Required by default.
* Example:

  ```python
  parser.add_argument('filename', type=str, help="Input file")
  ```

#### **Optional Arguments**

* Start with `-` or `--`.
* Example:

  ```python
  parser.add_argument('-v', '--verbose', action='store_true')
  ```

#### **Action Types**

* `store`, `store_true`, `store_false`, `append`, `count`, custom.

#### **Choices**

* Restrict values to a predefined list:

  ```python
  parser.add_argument('--mode', choices=['fast', 'slow'], help="Execution mode")
  ```

#### **Default Values**

* Provide a default:

  ```python
  parser.add_argument('--timeout', type=int, default=30, help="Timeout in seconds")
  ```

#### **Help and Formatting**

* Automatically generates usage and help messages.

***

### **Complete Example**

```python
import argparse

# Initialize parser
parser = argparse.ArgumentParser(
    prog="argparse_demo",
    description="Demonstrates argparse functionality",
    epilog="End of help message"
)

# Add arguments
parser.add_argument('input_file', type=str, help="File to process")
parser.add_argument('-o', '--output', type=str, help="Output file")
parser.add_argument('-v', '--verbose', action='store_true', help="Enable verbose mode")
parser.add_argument('--level', type=int, choices=[1, 2, 3], default=1, help="Processing level (default: 1)")

# Parse arguments
args = parser.parse_args()

# Use arguments
print(f"Input File: {args.input_file}")
print(f"Output File: {args.output}")
print(f"Verbose Mode: {args.verbose}")
print(f"Processing Level: {args.level}")
```
